user863492 user863492 - 23 days ago 5x
C++ Question

Abusing cin in while loops for int assignment

simply trying to compare two user defined vectors to see if they are equal, current code:

vector<int> ivec1, ivec2; //vectors, uninitialized

int temp1;

cout << "Enter integers to be stored in ivec1." << endl;

while(cin >> temp1) //takes input from user and creates new element in the vector to store it

int temp2;

cout << "Enter integers to be stored in ivec2." << endl;

while(cin >> temp2) //same as above with different vector

if(ivec1 == ivec2)
cout << "ivec1 and ivec2 are equal!" << endl;
cout << "ivec1 and ivec2 are NOT equal!" << endl;

So far it lets me assign values to ivec1 just fine, but as I exit the while loop by entering a letter to make cin fail, it skips the second while block. Out of curiosity I tried putting in other cin statements after the first while loop, and it ignores them all as well.

Does forcing cin to fail cause the program to ignore all other calls for it or something, or is there another problem? If so, how can I get this program to do what I want?

screenshot for your viewing pleasure:

*PS. having temp1 and temp2 was just me trying to figure out if using the same int for both assignment loops was causing the problem, anyway I just figured I'd leave it there


You would have to do cin.clear() to reset the stream state. Then you will have to make sure that the offending character is read from the stream (using one of the techniques described here), so that the next input operation does not fail as well.