> token ) -6ren">
gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:29:03 25 4
gpt4 key购买 nike

如果我这样做:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com