c++ - 从 istream 中提取失败后的字符串内容

标签 c++ extraction istream

如果我这样做:

ifstream stream("somefilewhichopenssuccesfully.txt");
string token;
if( stream >> token )
    cout << token;
else
    cout << token;

第二种情况下的输出是否保证为空字符串?我似乎无法在 cplusplus.com 上找到这个问题的答案。

谢谢!

最佳答案

Is the output in the second case guaranteed to be an empty string?

答案是:不,因为这取决于具体情况,如下所述。

因为 else block 只有在尝试从流中读取失败时才会执行,并且在读取过程中随时可能发生。

  • 如果第一次尝试失败,则不会从流中提取字符,因此 token 将为空(原样)。

    <
  • 如果多次读取失败,则 token 不会为空。它将包含到目前为止从流中成功读取的字符。

标准的 §21.3.7.9 节说,

Begins by constructing a sentry object k as if k were constructed by typename basic_istream::sentry k(is). If bool(k) is true, it calls str.erase() and then extracts characters from is and appends them to str as if by calling str.append(1,c). If is.width() is greater than zero, the maximum number n of characters appended is is.width(); otherwise n is str.max_size(). Characters are extracted and appended until any of the following occurs:

— n characters are stored;

— end-of-file occurs on the input sequence;

— isspace(c,is.getloc()) is true for the next available input character c.

After the last character (if any) is extracted, is.width(0) is called and the sentry object k is destroyed.

If the function extracts no characters, it calls is.setstate(ios::failbit), which may throw ios_base::failure (27.4.4.3).


另请注意,标准中的 §21.3.1/2 部分保证默认构造的字符串将为空。标准规定其大小将为零,即空。

关于c++ - 从 istream 中提取失败后的字符串内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5695705/

相关文章:

c++ - 如何检测强度梯度方向

c++ - 用于获取最大值及其在 vector 中的相应索引的模板函数

python - 从 zip 文件中提取文件并保留 mod 日期?

c++ - 如何检查cin中是否有任何东西[C++]

c++ - 使用 getline 处理重定向文件输入后使用 cin 进行键盘输入

C++ RAII 不工作?

c++ - 将 openCV 重映射与 float* 结合使用

full-text-search - 给定DOI或标题,从科学文献中提取摘要/全文

java - PDFBox - 获取单词位置(而不仅仅是字符')

c++ - 如何为自定义 istream/streambuf 实现 seekg()?