只要不配置流使用异常,就很容易区分EOF和其他错误。
在结尾处简单地检查
stream.eof()
即可。
在此之前仅检查失败/非失败,例如
stream.fail()
或
! stream
。请注意,
good
并非
fail
的相反。因此通常只应查看
fail
,而不是
good
。
编辑:
一些示例代码,即修改后的示例以区分数据中未正确指定的布尔值:
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
using namespace std;
bool throwX( string const& s ) { throw runtime_error( s ); }
bool hopefully( bool v ) { return v; }
bool boolFrom( string const& s )
{
istringstream stream( s );
(stream >> boolalpha)
|| throwX( "boolFrom: failed to set boolalpha mode." );
bool result;
(stream >> result)
|| throwX( "boolFrom: failed to extract 'bool' value." );
char c; stream >> c;
hopefully( stream.eof() )
|| throwX( "boolFrom: found extra characters at end." );
return result;
}
void readbools( istream& is )
{
string word;
while( is >> word )
{
try
{
bool const b = boolFrom( word );
cout << (b ? "T" : "F") << endl;
}
catch( exception const& x )
{
cerr << "!" << x.what() << endl;
}
}
cout << "- " << is.good() << is.eof() << is.fail() << is.bad() << "\n";
}
void testread( string const& s )
{
istringstream is( s );
readbools( is );
}
int main()
{
cout << string( 60, '-' ) << endl;
testread( "true false" );
cout << string( 60, '-' ) << endl;
testread( "true false tr" );
cout << string( 60, '-' ) << endl;
testread( "true false truex" );
}
示例结果:
------------------------------------------------------------
T
F
- 0110
------------------------------------------------------------
T
F
!boolFrom:无法提取“bool”值。
- 0110
------------------------------------------------------------
T
F
!boolFrom:末尾找到额外字符。
- 0110
编辑2:在发布的代码和结果中,添加了使用eof()
检查的示例,我忘记了。
编辑3:
以下对应示例使用OP提出的读取前跳过空白解决方案:
using namespace std;
void readbools( istream& is )
{
bool b;
while( is >> ws && !is.eof() && is >> b ) // <- Proposed scheme.
{
cout << (b ? "T" : "F") << endl;
}
if( is.fail() )
{
cerr << "!readbools: failed to extract 'bool' value." << endl;
}
cout << "- " << is.good() << is.eof() << is.fail() << is.bad() << "\n";
}
void testread( string const& s )
{
istringstream is( s );
is >> boolalpha;
readbools( is );
}
int main()
{
cout << string( 60, '-' ) << endl;
testread( "true false" );
cout << string( 60, '-' ) << endl;
testread( "true false tr" );
cout << string( 60, '-' ) << endl;
testread( "true false truex" );
}
示例结果:
------------------------------------------------------------
T
F
- 0100
------------------------------------------------------------
T
F
!readbools:无法提取“bool”值。
- 0110
------------------------------------------------------------
T
F
T
!readbools:无法提取“bool”值。
- 0010
主要区别在于,即使第三个值不正确(如"truex"
),该方法也会在第三种情况下产生3个成功读取的值。
也就是说,它无法将错误的规范识别为错误。当然,我写的代码不能正常工作并不意味着它不能正常工作。但是我很擅长编写代码,并且我找不到任何一种方法可以使用此方法检测"truex"
是否不正确(而基于读取单词的异常处理方法很容易实现)。因此,至少对我来说,基于读取单词的异常处理方法更简单,因为很容易使其正确运行。
fail()
的值,这意味着至少对于这个测试,fail()
可以区分两种情况。 - celtschk