我一直在學習 C ,并制作了一個簡單的控制臺應用程式。但是當我使用 if 陳述句檢查輸入是否為整數時,非整數字符似乎等于 0,所以當我輸入非整數字符時,它的行為就像我輸入了 0。我正在嘗試使它所以當我輸入 0 應用程式關閉但問題是當我輸入一個字符時應用程式也會關閉。
我可以嘗試在下面與您解釋更多。
int main()
{
// Use > SetConsoleTextAttribute(h,13); < for text color
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
int input;
std::cout << "Pleas enter (1 or 2).\n";
while(true)
{
// Set coler to default
SetConsoleTextAttribute(h,7);
std::cin >> input;
if(input == 0)
{
return(0); "<--- this is where I am trying to close the app."
}
if(input == 1)
{
// Set coler to green
SetConsoleTextAttribute(h,10);
std::cout << "hi\n";
}
if(input == 2)
{
// Set coler to green
SetConsoleTextAttribute(h,10);
std::cout << "bye\n";
}
// Check if input is to an integer
if(! std::cin >> input) "<--- this is where I am checking if input is to an integer"
{
// Set coler to red
SetConsoleTextAttribute(h,4);
// Explain the error
std::cout << "Error: input is not a number.\n";
// Clear the previous input
std::cin.clear();
// Discard previous input
std::cin.ignore(123, '\n');
continue;
}
// Check if input is to large
if(input > 2)
{
// Set coler to red
SetConsoleTextAttribute(h,4);
std::cout << "Error: input to large.\n";
continue;
}
// Check if input is to small
if(input < 0)
{
// Set coler to red
SetConsoleTextAttribute(h,4);
std::cout << "Error: input to small.\n";
continue;
}
}
return 0;
}
uj5u.com熱心網友回復:
這個操作
std::cin >> input;
有副作用。在您的程式中多次使用相同的代碼與只執行一次不同。
尤其,
if(! std::cin >> input)
沒有希望做你想做的事,因為
如果第一個資料輸入失敗,則您已經退出程式并且從未到達此位置。
如果第一個資料輸入成功,這
if不是檢查第一個資料輸入之后的狀態,它會嘗試從cin.
進行錯誤處理并替換第一個std::cin >> input;,不要只是將其粘貼到下面。
uj5u.com熱心網友回復:
在檢查輸入是否成功處理為整數input == 0 之前,您正在檢查是否。此外,請注意,std::cin >> input;后續if(! std::cin >> input)將讀取cin兩次,而不是一次。
std::cin >> input根據cppreference ,當您輸入可能導致失敗的輸入時,會發生以下情況:
如果提取失敗(例如,如果在需要數字的地方輸入了一個字母),則寫入
value并failbit設定為零。對于有符號整數,如果提取導致值太大或太小而無法放入值,std::numeric_limits<T>::max()或者std::numeric_limits<T>::min()(分別)被寫入并failbit設定標志。對于無符號整數,如果提取導致值太大或太小而無法放入值,std::numeric_limits<T>::max()則寫入并failbit設定標志。
因此,在您輸入類似的內容后將input == 0無法轉換為.true"cat"int
uj5u.com熱心網友回復:
您需要檢查讀取是否有效:
if (std::cin >> input) {
if(input == 1)
{
// Set coler to green
SetConsoleTextAttribute(h,10);
std::cout << "hi\n";
}
// etc
}
else {
// Input failed.
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/466909.html
