我正在創建一個簡單的控制檯應用程序,用於獲取用戶輸入的整數。當出現錯誤時返回第一條指令
我想要的狀態,以便它應該只是一個整數,它應該是不超過3和不小於0
我想出了到目前爲止的代碼是:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int uinval;
while (true) {
string tempoval;
cout << "Please enter a value between 0-3:\n>";
cin >> tempoval;
stringstream ss(tempoval);
if (ss >> uinval)
{
break;
cout << "Entered an invalid value";
}
while (true)
{
if (uinval < 0 || uinval > 3)
break;
cout << "Value must be between 0-3";
}
cout << "You have entered:" << uinval;
return 0;
}
當我輸入像a,b,c,d這樣的非整數值時,這是有效的。但是當我輸入-1或4作爲值時它不起作用。
我不確定,也許我把自己與while循環混淆了。
確保您正確縮進代碼。如果你的'}'總是與時間排在一起,或者它屬於的話,那麼while循環變得不那麼令人困惑。 – wolfgang 2013-05-14 13:36:55
也可以使用'{}'作爲單行if語句。它提高了可讀性和可維護性 – stefan 2013-05-14 13:39:36
@stefan它也是聖戰的主題;-) – wolfgang 2013-05-14 13:40:32