0

I am trying to see what is the easiest way to read input from a text file with information:

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

Normally this should be very simple but I need to account for those first 2 lines which contain 2 different numbers needed.

So far I have set up:

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

}

So this is a round about way of getting those first 2 numbers but I believe there should be an easier way of doing this. Any suggestions or if someone can point me in the right direction

4

1 に答える 1

2

ループの前に 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 に答える