gpt4 book ai didi

c++ - 使用 noskipws 从 ifstream 读入字符串时为空字符串

转载 作者:行者123 更新时间:2023-11-27 23:26:54 26 4
gpt4 key购买 nike

最初问 here .

如果我使用以下代码将“Hello world”发送到 cin...

string str,msg;
getline(cin,str);
stringstream ss(str);
char c;
while(ss >> noskipws >> c)
msg += c;

...结果为 msg = "Hello World"

但是如果我使用 string c 而不是 char cmsg 是空的。

我正在编译:gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3

为什么我得到一个空字符串?

最佳答案

这是一个有趣的 quote from cplusplus.com :

Notice that many extraction operations consider the whitespaces themselves as the terminating character, therfore, with the skipws flag disabled, some extraction operations may extract no characters at all from the stream.

如果要将标记提取到字符串中,请删除 noskipws

通常,您应该仔细考虑,然后坚持{基于行、基于标记或基于字符}提取之一。

关于c++ - 使用 noskipws 从 ifstream 读入字符串时为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631782/

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