C++ 中的 cin.get() 问题



我有以下代码:

#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'); // **Line 2**
        {
            cin.ignore(1000,'n');
            cout << "Enter y again: ";
            cin >> y;   
        }
        cout << x << ", " << y;
    _getch();
    return 0;
}

执行时,我可以输入 x 值,它按预期忽略第 1 行。但是,当程序要求 y 值时,我输入了一个值,但程序没有忽略第 2 行的 while?我不明白,1号线2号线有什么区别?我怎样才能让它按预期工作?

if (cin.get() != 'n'); // **Line 2**
// you have sth here -^

删除该分号。如果它存在,if语句基本上什么都不做。
此外,您没有测试用户是否真的输入了一个数字......如果我改为输入'd'怎么办?:)

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.

最新更新