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 行的 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.
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- Cpp-Tuple使用带有变量的get
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 编写 cin.get() 以接收字符数组时出现问题
- Visual Studio 2017 中的 cpprestapi 问题找不到 POST/GET 常量
- 我在这里使用"cin.get"有什么问题?
- 在 xcode 中使用 get 函数时面临问题
- C++HTTP GET请求问题
- C++ 中的字符串:good() 和 get() 的问题
- c++中在跳出循环时cin.get()递增的问题
- C++ 中的 cin.get() 问题