简体   繁体   English

C ++:为什么getline()不打印输入字符串的最后一个单词?

[英]C++: Why won't getline() print the last word of the input string?

i'm trying to get my program to read a string and then output each word on an individual line. 我试图让我的程序读取一个字符串,然后在单独的一行上输出每个单词。 When I call this function it is not printing the last word of the sentence. 当我调用此函数时,它不会打印句子的最后一个单词。 I have not been able to find an answer to this problem. 我无法找到此问题的答案。

For example: 例如:

Input: 输入:

Hello there my friend 你好,我的朋友

Output: 输出:

Hello 你好

there 那里

my 我的

Here is my code: 这是我的代码:

istream& operator >> (istream& in, FlexString& input) {
    std::string content;
    while (std::getline (in,content,' ')) {
        cout << content << endl;
    }

    return in;
}

I'm new to C++ so this may be dumb, but I tried adding another cout call to print content on the next line after the while loop but it won't print it for some reason. 我是C ++的新手,所以这可能很愚蠢,但是我尝试在while循环之后添加另一个cout调用以在下一行上打印内容 ,但是由于某种原因它不会打印它。

getline didn't skip the last word. getline没有跳过最后一个单词。 It's still waiting for you to finish it. 它仍在等待您完成它。 You selected the space character ( ' ' ) as the delimiter, so getline is going to read until if finds a space (not a tab or a newline), or until the input stream ends. 您选择了空格字符( ' ' )作为分隔符,因此getline将读取直到找到空格(不是制表符或换行符),或者直到输入流结束为止。 Your loop isn't going to stop at the end of the line either, like you seem to be expecting. 您的循环也不会在行尾停止,就像您期望的那样。 It is going to keep reading until the stream ends. 它会一直读取直到流结束。

If you want to read a single line, and then separate the line word by word, then just call getline once, with the \\n delimiter (which is the default). 如果要读取一行,然后逐行分隔行,则只需使用\\n分隔符(这是默认值)调用一次getline Then use an istringstream to separate the resulting string word by word. 然后使用istringstream分隔所得字符串。

std::string line;
std::getline(in, line);
std::istringstreaam iss(line);
std::string content;
while (iss >> content)
    std::cout << content << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM