How to identify end of entries in C ++ using cin

0

In my college work, we submit our code to a platform that "corrects" the code automatically (inserts the entries in the code and compares the outputs generated with the template).

To get the entries, we always use the command cin .

To exemplify my problem: Suppose I have the following entry:

1 1 
2 3
5 8
0 0

And you have to output the sum of each pair of numbers, until both are 0, which identifies the end of the entries.

The code would be something like:

#include<iostream>
using namespace std;

int main(){

   int x,y;

   do{

       cin >> x;
       cin >> y;

       if(x != 0 && y != 0){

          z = x + y;
          cout << z << endl;

       }//fim if

   }while(x != 0 && y != 0);//fim do.while

   return 0;

}//fim main

Now, I need to solve the same problem, however, the end of the entries is demarcated by the end of the file (as opposed to having the input pair 0,0).

What condition do I have to put in place of while(x != 0 && y != 0); to make this happen?

    
asked by anonymous 24.06.2018 / 00:45

1 answer

1

When a read is not possible the cin is marked as invalid, which when evaluated as boolean will give false. This allows you to do things like:

if (cin >> x){

}

That will only enter if if it was possible to read to the x variable. Extrapolating this idea to your program you can change your while to:

while (cin >> x && cin >> y)

It will run as long as it is possible to read both x and y .

Complete code for reference:

#include<iostream>
using namespace std;

int main(){
   int x, y;

   while (cin >> x && cin >> y){
       int z = x + y;
       cout << z << endl;    
   }

   return 0;    
}
    
24.06.2018 / 02:50