[英]using cin to close a while loop
我正在嘗試使用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;
}
您應該將while循環內的代碼更改為類似以下內容:
cout<<"that is not a number, do not pass go, do not collect $200 but DO try again."<<endl;
if (!cin) { // we enter the if statement if cin is in a "bad" state.
cin.clear(); // first we clear the error flag here
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // now we skip the input,
// that led to the invalid state
}
cin>>mph;
如果輸入字符串並嘗試使用cin
將其讀入float
,則cin
進入無效狀態,並拒絕讀取任何輸入,直到清除為止。
這就是我上面建議的代碼試圖解決的問題。 請注意,您必須包括<limits>
才能使其起作用。
有關清除輸入流的更多信息的相關鏈接: 為什么此cin讀數卡住了?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.