[英]cin.ignore() function in C++ not working for the whole stream
我試圖安全地輸入 1 到 25 之間的整數,但我被告知要使用的代碼無法正常工作。 那是代碼:
*int SafelyInputInteger(int lowerBound, int upperBound)
{
int intNumber;
do {
cout<<"Input a number: "; cin>>intNumber;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
continue;
}
} while((intNumber<lowerBound)||(intNumber>upperBound));
return intNumber;
}
int main()
{
int height;
height=SafelyInputInteger(1,25);
cout<<"Height is: "<<height<<endl;
return 0;
}*
我得到的錯誤如下:錯誤:'numeric_limits' 未在此范圍內聲明錯誤:'>' 之前的預期主表達式標記錯誤:沒有匹配的函數調用'max()'
您提到的確切錯誤是在使用 GCC 編譯且不包括<limits>
標頭時發生的。
<source>: In function 'int SafelyInputInteger(int, int)':
<source>:16:24: error: 'numeric_limits' was not declared in this scope
cin.ignore(numeric_limits<streamsize>::max(),'\n');
^~~~~~~~~~~~~~
<source>:16:49: error: expected primary-expression before '>' token
cin.ignore(numeric_limits<streamsize>::max(),'\n');
^
<source>:16:56: error: no matching function for call to 'max()'
cin.ignore(numeric_limits<streamsize>::max(),'\n');
在此處查看現場演示。 使用的編譯器版本:GCC 8.2
包含<limits>
標頭可解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.