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

标签 c++ getline istringstream

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

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/

相关文章:

C++:无法使用字符串流操作打开文件

c++ - 使用 glew 时 opengl 崩溃

c++ - 没有匹配的函数来调用 getline()

c++ - 使用 boost asio 的 HTTPS POST 请求

c++ - ifstream getline 问题(它只读取第一行)

c++ - C++中的Getline错误

c++ - 初学者 : on reading in from file and using istringstream

c++ - 读取文件内容时未定义的字符,文件末尾没有新行

c++ - 在 C++ 中没有类的情况下从 main() 访问函数内部的静态变量

c++ - 为什么成员初始值设定项不能使用括号?