【发布时间】:2015-01-19 18:33:52
【问题描述】:
我对 cin 的一些命令有疑问。我对 c++ 还是很陌生,所以请耐心等待。
我正在做一个简单的计算程序,用户输入一个值,程序使用输入进行计算。我正在尝试创建一个循环来检查输入以确保用户输入和编号。经过一番研究,我发现使用cin.clear 和cin.ignore 会清除以前的输入,以便用户可以在循环检查后输入一个新值以查看它是否不是数字。它运行良好,除非用户输入大于 1 个字母的单词。然后它循环并一次删除每个字母,直到前一个 cin 被清除。有没有办法一次删除整个单词而不是一个字符?我觉得我错误地解释了 cin 命令的实际作用。
这里是有问题的代码:
//Ask the user to input the base
cout << "Please enter the Base of the triangle" << endl;
cin >> base;
//A loop to ensure the user is entering a numarical value
while(!cin){
//Clear the previous cin input to prevent a looping error
cin.clear();
cin.ignore();
//Display command if input isn't a number
cout << "Not a number. Please enter the Base of the triangle" << endl;
cin >> base;
}
【问题讨论】:
-
如何定义'base'?
-
Base 在全局部分被定义为双精度
-
我通常发现最好的方法是将一整行输入作为字符串读取,然后自己解析(这样您就可以完全控制检测任何无效输入) .