[英]C++ cin.fail() question
運行以下代碼並輸入數字時,它可以正常工作。 但是當輸入一個字母時,程序進入一個無限循環,顯示“輸入一個數字(0退出):cin失敗。”
我的意圖是處理cin失敗案例並再次提示用戶。
int number;
do{
cout << "Enter a number (0 to exit): ";
cin >> number;
if(cin.fail()){
cout << "cin failed." << endl;
cin.clear();
}else{
cout << "cin succeeded, " << number << " entered." << endl;
}
}while(number != 0);
你需要使用cin.ignore清除cin中的行,除了清除流狀態(這是cin.clear所做的)。
我有幾個實用程序函數,以使這更容易(你會特別感興趣的clearline ,它清除流狀態和當前行)和幾乎所有你想要的確切示例。
您的代碼,或多或少,使用我的clearline :
#include "clinput.hpp" // move my file to a location it can be used from
int main() {
using namespace std;
while (true) {
cout << "Enter a number (0 to exit): ";
int number;
if (cin >> number) {
cout << "Read " << number << '\n';
if (number == 0) {
break;
}
}
else {
if (cin.eof()) { // tested only *after* failed state
cerr << "Input failed due to EOF, exiting.\n";
return 1;
}
cerr << "Input failed, try again.\n";
clearline(cin); // "cin >> clearline" is identical
}
}
return 0;
}
這里仍然存在一個潛在的問題(在我的clinput_loop.cpp中使用blankline修復),在緩沖區中留下輸入,這將使后來的IO搞砸(參見示例會話中的“42 abc”)。 將上面的代碼提取到一個單獨的,自包含的函數中留給讀者練習,但這是一個骨架:
template<class Type, class Ch, class ChTr>
Type read(std::basic_istream<Ch,ChTr>& stream, Ch const* prompt) {
Type value;
// *try input here*
if (could_not_get_input or more_of_line_left) {
throw std::runtime_error("...");
}
return value;
}
template<class Type, class Ch, class ChTr>
void read_into(
Type& value,
std::basic_istream<Ch,ChTr>& stream,
Ch const* prompt
) {
value = read<Type>(stream, prompt);
}
使用示例:
int n;
try {
read_into(n, std::cin, "Enter a number: ");
}
catch (std::runtime_error& e) {
//...
raise;
}
cout << "Read " << n << '\n';
為后代提取的clearline函數,以防上面的鏈接中斷(並稍微更改為自包含):
#include <istream>
#include <limits>
template<class C, class T>
std::basic_istream<C,T>& clearline(std::basic_istream<C,T>& s) {
s.clear();
s.ignore(std::numeric_limits<std::streamsize>::max(), s.widen('\n'))
return s;
}
如果你不習慣它,模板的東西有點混亂,但並不難:
std::basic_istream<char, std::char_traits<char> >
的typedef std::basic_istream<char, std::char_traits<char> >
std::basic_istream<wchar_t, std::char_traits<wchar_t> >
'\\n'
在適當時變為L'\\n'
clearline(stream)
或 stream >> clearline
,與其他操縱stream >> clearline
如std :: endl , std :: ws或std :: boolalpha相比較 這可能是你打算做的:
#include <iostream>
using namespace std;
int main ()
{
int i;
do {
if (cin.fail())
{
cin.ignore(255);
cin.clear();
}
cout << "Please enter an integer value: ";
cin >> i;
} while ( cin.fail() );
cout << "The value you entered is " << i;
return 0;
}
這是cin.fail()的簡單示例。它將處理輸入,直到提供有效的整數值
#include <iostream>
using namespace std;
int main()
{
int j;
int i;
i = 0;
while (1) {
i++;
cin >> j;
if (cin.fail()) return 0;
cout << "Integer " << i << ": " << j << endl;
}
}
輸入:
42 51 85你好85
輸出:
整數1:42
整數2:51
整數3:85
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.