简体   繁体   中英

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.

getline didn't skip the last word. 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. 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). Then use an istringstream to separate the resulting string word by word.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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