0

我正在尝试查看从包含信息的文本文件中读取输入的最简单方法:

7
12
v1-v2 7
v1-v3 11
v1-v4 1
v2-v4 12
v2-v5 5
v3-v4 8
v3-v6 10
v4-v5 6
v4-v6 3
v4-v7 4
v5-v7 9
v6-v7 2

通常这应该很简单,但我需要考虑前两行,其中包含所需的 2 个不同数字。

到目前为止,我已经设置:

int nodes;
int lines;
string line;

int count=0;

while(cin) {
  getline(cin, line);

  for(int i = 0; i < line.length(); i++) {
    if(count >2)
        break;

   if(! (s[i] >= '0' && s[i] <= '9') 
     break;
   else if(count=0) {
     nodes = s[i]-'0';
   }
   else
     lines = s[i]-'0';

     count++;
  }

 //Space for code to account for other lines

}

所以这是一个关于获得前两个数字的方法,但我相信应该有一种更简单的方法来做到这一点。任何建议或是否有人可以指出我正确的方向

4

1 回答 1

2

为什么不读取循环前的两个数字:

cin >> nodes >> lines;

如果输入中没有任何内容,则变量将设置为 0。

如果您需要以更好的方式处理此问题,您可以执行类似的操作:

if (cin) cin >> nodes;
else { /* handle error situation */ }

if (cin) cin >> lines;
else { /* handle error situation */ }
于 2013-03-14T16:20:05.700 回答