本人初学C++,做一个C++primer的课后习题,搞了半天还是不能通过测试,好心的帮我看一下原因。
原题:
编写一个函数,其唯一的形参和返回值都是istream&类型。该个函数应一直读取流直到到达文件结束符为止,还应将读到的内容输出到标准输出中。最后,重设流使其有效,并返回该流。
我写的程序:
#include <iostream>
#include <string>
#include <stdexcept>
using std::runtime_error;
using std::cout;
using std::cin;
using std::endl;
using std::istream;
using std::cerr;
istream &test(istream &);
istream &test(istream & input)
{
int a;
while(input>>a, !input.eof())//这是“,”运算符
{
if (input.bad())
throw runtime_error("IO stream corrupted");
if (input.fail())
{
cerr<<"bad data, try again\n";
input.clear(istream::failbit);
continue;
}
cout<<"reading a int variable is successful\n the number is "<<a<<endl;
}
return input;
}
int main()
{
test(cin);
return 0;
}
出现错误:
当输入一个字符时,一直死循环输出:bad data, try again
大家帮忙看一下吧。