从Stdin读取文本文件

时间:2013-03-14 16:14:25

标签: c++ file stdin

我正在尝试查看从文本文件中读取信息的最简单方法是什么:

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行,其中包含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

}

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

1 个答案:

答案 0 :(得分:2)

为什么不在循环之前读取这两个数字:

cin >> nodes >> lines;

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

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

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

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