【发布时间】:2014-03-02 01:57:17
【问题描述】:
我正在尝试使用 while 循环来验证我的用户输入。请参阅下面的代码/while 循环。我希望他们输入一个浮点数,并且我正在尝试验证他们是否输入了一个数字而不是一个字母/句子。我认为这个循环应该可以工作,但是当我运行它时,如果我输入一个数字,它会在到达程序末尾之前出现,如果我输入一个字符串,它会触及cout 语句,无法请求cin,并且然后验证循环。如果您能解释发生了什么、为什么会发生以及如何解决它,我将不胜感激。
#include <iostream>
using namespace std;
int main()
{
float mph, i = 0;
cout << "this program will calculate the distance a train will travel in a given amount of time." << endl;
cout << "What is the speed of the vehicle in mph? ";
cin >> mph;
cout << endl;
while (mph > -3.4E-38 && mph < 3.4E38);
{
cout << "that is not a number, do not pass go, do not collect $200 but DO try again." << endl;
cin >> mph;
// trace statement to check whats happening in the loop
cout << "trace: " << mph << "faluer: " << i << endl;
i++;
}
cout << "works twice" << endl;
system("pause");
return 0;
}
【问题讨论】:
-
Raphael,我想我有点理解你的意思(我是 C++ 新手)但也许我问错了问题。我想要做的是以最简单的方式验证用户输入。我要求用户提供数字,我想使用 while 语句来检查他是否输入了一个数字,不管它是整数还是浮点数,只要它不是字符串或字符。使用 while 语句执行此操作的最佳方法是什么?我认为我的 while 声明做到了,但也许这不是最好的方法?验证用户输入数字的最佳方法是什么?
-
如果您指的是 Raphael 发布的答案,那么这正是它的作用,他还解释了它是如何工作的
标签: c++ while-loop