Problem with cin.get() in C++?
I have the following code:
#include <conio.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int x = 0;
cout << "Enter x: " ;
cin >> x;
if (cin.get() != '\n') // **line 1**
{
cin.ignore(1000,'\n');
cout << "Enter number: ";
cin >> x;
}
double y = 0;
cout << "Enter y: ";
cin >> y;
if (cin.get() != '\n'); // 开发者_Python百科**Line 2**
{
cin.ignore(1000,'\n');
cout << "Enter y again: ";
cin >> y;
}
cout << x << ", " << y;
_getch();
return 0;
}
When executed, I can enter x value and it ignores Line 1 as I expected. However, when the program asks for y value, I inputed a value but the program did not ignore the while at Line 2? I don't understand, what is the difference between Line 1 and Line 2? And how can I make it work as expected?
if (cin.get() != '\n'); // **Line 2**
// you have sth here -^
Remove that semicolon. If it is there, the if
statement basically does nothing.
Also, you're not testing wether the user really inputs a number... what if I input 'd'
instead? :)
while(!(cin >> x)){
// woops, something has gone wrong...
// display a message to tell the user he made a mistake
// and after that:
cin.clear(); // clear all errors
cin.ignore(1000,'\n'); // ignore until newline
// and try again, while loop yay
}
// now we have correct input.
精彩评论