简体   繁体   English

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

[英]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'); // **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. 执行后,我可以输入x值,并且它会按预期忽略第1行 However, when the program asks for y value, I inputed a value but the program did not ignore the while at Line 2 ? 但是,当程序要求输入y值时,我输入了一个值,但程序并没有忽略第2行 I don't understand, what is the difference between Line 1 and Line 2 ? 我不明白, 1 线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. 如果存在,则if语句基本上什么也不做。
Also, you're not testing wether the user really inputs a number... what if I input 'd' instead? 另外,您是否在测试用户是否真的输入了数字……如果我输入'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