Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::getline在最后一次出现分隔符后跳过来自std::cin的输入,但不使用来自std::istringstream的输入_C++_Getline_Istringstream - Fatal编程技术网

C++ std::getline在最后一次出现分隔符后跳过来自std::cin的输入,但不使用来自std::istringstream的输入

C++ std::getline在最后一次出现分隔符后跳过来自std::cin的输入,但不使用来自std::istringstream的输入,c++,getline,istringstream,C++,Getline,Istringstream,我需要读取一些由空格分隔的输入,我用于此的主要结构是: while(std::getline(std::cin, s, ' ')){ std::cout << s << std::endl; } while(std::getline(std::cin,s,,)){ 标准::cout 我的问题是:为什么使用分隔符从std::cin读取时会跳过最后一次出现分隔符后的输入,而从std::istringstream读取时则不会 没有 在您的第一个示例中: while(s

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

while(std::getline(std::cin, s, ' ')){
    std::cout << s << std::endl;
}
while(std::getline(std::cin,s,,)){ 标准::cout 我的问题是:为什么使用分隔符从
std::cin
读取时会跳过最后一次出现分隔符后的输入,而从
std::istringstream
读取时则不会

没有

在您的第一个示例中:

while(std::getline(std::cin, s, ' ')){
    std::cout << s << std::endl;
}
第一个while中的
std::getline
从示例语句中删除新行。然后根据一些基本规则提取项目

规则如下:


在第一个示例中,尝试将
std::cin>>std::skipws;
放在循环之前,将
std::cin>>std::noskipws;
放在循环之后。看看它是否有效。第一个示例正在等待看到一些
'
,但在行尾只看到
'
,因此它仍在等待下一行的另一个
'
第二种情况是,它到达流的末尾,因此返回它已经返回的内容,即使没有尾随的
'
。让我猜猜,您在使用
std::cin
时没有终止输入流。按enter键不会阻止getline进一步读取和等待输入。感谢您的评论!确实是由于未正确执行命令而导致的错误终止输入,手动输入\n将导致在第一个示例中打印整个输入,即“这是一些文本\n”值得一提的是,在第一个示例中,
getline
只是在等待进一步的输入以完成字符串的读取。缺少EOF确实是问题所在,我很愚蠢。不过感谢您的回答!它肯定已经解决了问题。
while(std::getline(std::cin, s, ' ')){
    std::cout << s << std::endl;
}
while (std::getline(std::cin, line)) {
    std::istringstream iss(line);

    while (std::getline(iss, s, ' ')) {
        std::cout << s << std::endl;
    }
}
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.