从 istream 提取失败后的字符串内容
如果我这样做:
ifstream stream("somefilewhichopenssuccesfully.txt");
string token;
if( stream >> token )
cout << token;
else
cout << token;
第二种情况的输出是否保证为空字符串?我似乎无法在 cplusplus.com 上找到这个问题的答案。
谢谢!
If I do this:
ifstream stream("somefilewhichopenssuccesfully.txt");
string token;
if( stream >> token )
cout << token;
else
cout << token;
Is the output in the second case guaranteed to be an empty string? I can't seem to find the answer to this on cplusplus.com.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案是:不,因为这取决于情况,如下所述。
因为只有当尝试从流中读取失败时才会执行 else 块,并且这种情况可能在读取过程中的任何时候发生。
token
将为空(就像以前一样)。如果在几次读取后失败,那么
token
将不为空。它将包含迄今为止从流中成功读取的字符。标准第 §21.3.7.9 节规定,
另请注意,标准中的第 §21.3.1/2 节保证默认构造的字符串将为空。标准说它的大小将为零,这意味着,空的。
The answer is : no, because it depends, as described below.
Since
else
block will be executed only if an attempt to read from the stream fails, and that can occur anytime in the course of reading.If it fails at the very first attempt, then there is no character extraction from the stream, and hence
token
will be empty (as it was).If it fails after few reads, then
token
will not be empty. It will contain the characters successfully read so far from the stream.The section §21.3.7.9 from the Standard says,
Also note that the section §21.3.1/2 from the Standard guarantees that the default constructed string will be empty. The Standard says its size will be zero, that means, empty.
我删除了原来的答案,因为我想测试一下。这就是我所看到的,如果读取时出现错误(在此上下文中不计算 EOF),原始字符串将被修改,分支将看到修改后的版本。为了测试,我执行了以下操作,创建了一个 2Gb 文件(
touch
然后truncate
),读取上面的代码。当代码运行时,删除该文件(这应该设置failbit
- 我认为)。立即停止读取,但字符串被修改 - 它具有更大的大小。对我来说,这表明即使流操作失败,字符串也会被修改。
I deleted my original answer because I wanted to test this. This is what I see, if there is an error whilst reading (EOF is not counted in this context), the original string is modified and the branch sees the modified version. To test I did the following, created a 2Gb file (
touch
thentruncate
), the above code to read. Whilst the code was running, removed the file (this should set thefailbit
- I think). Immediately stops reading, but the string is modified - it has a larger size.To me this indicates that the string is modified even if the stream operation fails.
不会,即使操作失败,字符串也会包含到目前为止提取的字符。
该标准规定(§21.4.8.9):
No, even if the operation fails, the string will contain the characters extracted so far.
The standard says (§21.4.8.9):