How to identify end of C++ entries using Cin

Asked

Viewed 570 times

0

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

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

To illustrate 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 the two 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 marked by the end of the file (as opposed to having the input pair 0.0).

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

1 answer

1

When a reading is not possible cin is marked as invalid, which when rated as boolean will turn out to be false. This allows you to do things like:

if (cin >> x){

}

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

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

Which will run as long as it is possible to read so much to x as 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;    
}
  • I have a question. C++ gives some assurance that the first cin will be executed first?

  • @Henriqueschiesspertussati Yes because the condition is interpreted from left to right and with the logical operator and(&&). For this reason the first is always the cin>>x and only if this is successfully read the cin>>y.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.