#include <iostream>
#include <vector>
usingnamespace std;
int main (void)
{
vector<int> ivec1, ivec2;
int num;
//initializing ivec1
cout << "Enter the elements of ivec1, Q to stop"<< endl;
while(cin >> num)
{
ivec1.push_back(num);
}
cin.sync();
//initializing ivec2
cout << "Enter the elements of ivec2, Q to stop" << endl;
while(cin >> num)
{
ivec2.push_back(num);
}
//compare and output conclusion
cout << "ivec1 and ivec2, ";
if(ivec1 == ivec2)
cout << "The are completely equal!!" << endl;
else
cout << "They are not equal!!" << endl;
return 0;
}
e...visual c++ 6.0
here is the excute output:
Enter the elements of ivec1, Q to stop
1
1
1
1
q
Enter the elements of ivec2, Q to stop
ivec1 and ivec2, They are not equal!!
Press any key to continue
when i use "cin.clear()" to instead "cin.sync"...doesn't work!:
Enter the elements of ivec1, Q to stop
2
2
2
2
q
Enter the elements of ivec2, Q to stop
ivec1 and ivec2, They are not equal!!
Press any key to continue
when i use "cin.ignore(1000, '\n')"....still doesn't work!
Enter the elements of ivec1, Q to stop
3
3
3
3
q
Enter the elements of ivec2, Q to stop
ivec1 and ivec2, They are not equal!!
Press any key to continue
Chervil, Andy, Catfish.....I'm very appreciate about your reply.
while(cin >> num)
The end condition for this loop is when the fail flag is set for the cin stream.
Before you can do any futher input from the stream, you need to clear the flag(s).
add this before the second input: cin.clear(); to clear the error flags
and cin.ignore(1000, '\n'); to get rid of the unwanted input from the buffer.
On line 12, you're using operator>> to extract ints from cin. But 'Q' is not an int, so if you enter it at the command line then the extraction will fail, putting cin into a fail state. Once that has happened, all subsequents cin calls will fail.
The quickest solution would be to select an int value to use as the sentinal. Perhaps -1? And use that to terminate the loop.
If you want to use Q to quit the loop, then you will need to read strings and then convert the numbers from the ascii string reprentation to int yourself. Using failure to terminate a loop is not a good idea.