gpt4 book ai didi

c++ - std::getline 在最后一次出现定界符后跳过来自 std::cin 的输入,但不使用来自 std::istringstream 的输入

转载 作者:搜寻专家 更新时间:2023-10-31 01:36:40 24 4
gpt4 key购买 nike

我需要读取一些由空格分隔的输入,我为此使用的主要结构是:

while(std::getline(std::cin, s, ' ')){
std::cout << s << std::endl;
}

对于输入:“这是一些文本”

S 的输出将是:“this”、“is”、“some”,从而跳过最后一个空格后的最后一段输入。

我也想在我的程序中包含最后一段输入,所以我去寻找解决方案并找到了以下内容:

while (std::getline(std::cin, line)) {
std::istringstream iss(line);

while (std::getline(iss, s, ' ')) {
std::cout << s << std::endl;
}
}

对于输入:“这是一些文本”

S 的输出将是:“this”、“is”、“some”、“text”,这正是我想要的。

我的问题是:为什么从带定界符的 std::cin 读取会跳过最后一次出现定界符后的输入,而从 std::istringstream 读取则不会?

最佳答案

My question is: why does reading from std::cin with a delimiter skip the input after the last occurrence of the delimiter, but reading from std::istringstream does not?

不是。

在你的第一个例子中:

while(std::getline(std::cin, s, ' ')){
std::cout << s << std::endl;
}

您专门从换行符中读取由单个空格分隔的项目。因为该行(表面上)以换行符结束,所以它永远不会完成从输入字符串中提取的操作,因为它需要 ' ' 或 EOF。

在你的第二个例子中:

while (std::getline(std::cin, line)) {
std::istringstream iss(line);

while (std::getline(iss, s, ' ')) {
std::cout << s << std::endl;
}
}

第一个 while 中的 std::getline 将从您的例句中去除换行符。然后根据一些基本规则提取项目。

这里是规则(from cppreference) :

Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)
a) end-of-file condition on input, in which case, getline sets eofbit.
b) the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.
c) str.max_size() characters have been stored, in which case getline sets failbit and returns.

关于c++ - std::getline 在最后一次出现定界符后跳过来自 std::cin 的输入,但不使用来自 std::istringstream 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35268604/

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