使用 cin 对象进行输入验证并清除缓冲区(c++)
以前我是一名 C 程序员(想了解更多关于系统编程的知识,但不想进入汇编,所以我选择了 C)更多,但后来在我的大学我必须学习 C++,我实际上很难使用cin
和 cout
对象,因为与我信任的 printf()
、 scanf()
相比,它有一些变化, getchar()
宏C.这是代码。
代码
int main(void)
{
using namespace std;
cout << "What is the number?\n\n";
cout << "#Number :";
cin >> num;
while(cin.fail())
{
cin.clear();
cin.ignore(1000 , '\n');
cout << "Please enter a number\n\n";
cout << "#Number :";
cin >> num;
}
return 0;
}
问题
1.)我希望此代码向用户询问一个数字(小于且大于或等于0),当用户输入字符或字符串时,我希望它提醒用户,清除输入缓冲区并重新提示用户输入新值,直到它是数字。
2.)所以我只是谷歌搜索并找到一个宣扬该方法的页面,所以我只是按照方法进行操作,但失败了。我不知道为什么一旦我运行这段代码,输入一个字符,它会导致输出无限循环请输入一个数字
。我在这段代码中犯了任何错误吗?
感谢您花时间阅读我的问题
P/S:我正在将 CodeBlocks 与 minGW 编译器一起使用。
Previously I'm a C programmer(wanna know more about system programming but don't wanna go into assembly so i choose C) more but later on in my University I have to take C++ , I'm actually having a hard time on using the cin
and cout
object as it has some changes compare to my trusted printf()
, scanf()
, getchar()
macro in C . Here's the code.
The Code
int main(void)
{
using namespace std;
cout << "What is the number?\n\n";
cout << "#Number :";
cin >> num;
while(cin.fail())
{
cin.clear();
cin.ignore(1000 , '\n');
cout << "Please enter a number\n\n";
cout << "#Number :";
cin >> num;
}
return 0;
}
The Question
1.)I want this code to ask for a number from user ( less than and more than or equal to 0) , when user enter a character or string , i want it to alert user about it , clear the input buffer and reprompt user for a new value until it's a number.
2.)So i just googling around and find a page preaching the method , so i just follow the way but it failed . I've no idea why once i run this code , type in a character it will causes infinite looping of the output Please enter a number
.Any mistake done by me in this code??
Thanks for spending time reading my problem
P/S : I'm using CodeBlocks with minGW compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你没有说它是如何失败的,所以很难说出你的问题是什么
是。事实上,您从不声明
num
是一个明显的问题。和如果您输入的行长度超过 1000 个字符,也会失败。
C++ 中更惯用的解决方案是使用 std::getline 逐行读取输入,然后使用 std::istringstream 将行转换为数字。
You don't say how it failed, so it's difficult to say what your problem
is. The fact that you never declare
num
is one obvious problem. Andit will fail if you enter a line longer than 1000 characters as well.
A more idiomatic solution in C++ would be to read the input line by line, using
std::getline
, and then usingstd::istringstream
to convert the line into a number.使用格式化输入的标准方法是在操作本身的条件检查中。此外,您需要读取整行并尝试解析它,而不是逐个提取令牌。例如,像这样:
随意在错误分支中添加进一步的诊断输出。
The standard way to use formatting input is inside a conditional check on the operation itself. Also, you'll want to read an entire line and attempt to parse that rather than extract token by token. E.g. like this:
Feel free to add further diagnostic output in the error branch.