繁体   English   中英

在C ++中使用cin.get()有问题吗?

[英]Problem with cin.get() in C++?

我有以下代码:

#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行 我不明白, 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM