0
我試圖驗證我的用戶輸入使用while循環。請參閱下面的代碼/ while循環。我希望他們輸入一個浮點數,我試圖驗證他們輸入了一個數字,而不是一個字母/句子。我認爲這個循環應該工作,但是當我運行它時,如果我輸入一個數字,它會在達到程序結束前彈出,如果我輸入一個字符串,它會觸及cout
語句,但無法請求cin
,然後驗證循環。如果你能解釋什麼和爲什麼發生以及如何解決它,我會非常感激。使用cin關閉while循環
#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;
}
拉斐爾,我想我有點下架你的意思(我是新的C++),但也許我問錯了問題。我試圖做的是以最簡單的方式驗證用戶輸入。我要求用戶提供數字,我想用while語句來檢查他是否輸入了一個數字,不管它是整數還是浮點數,只要它不是字符串或字符。用while語句做這件事的最好方法是什麼?我認爲我的一段時間的聲明是這樣做的,但也許這不是最好的方式去做呢?驗證用戶輸入數字的最佳方法是什麼? – James
如果你指的是Raphael發佈的答案,那麼這正是它所做的,他解釋了它是如何工作的 –