tags:

views:

158

answers:

2

I'm beginner to C++ and I wonder how to do this. I want to write a code which take in a text line. E.g. "Hello stackoverflow is a really good site"

From the output I want only to print out the first three words and skip the rest.

Output I want: "Hello stackoverflow is"

If it was Java I would've used the string split(). As for C++ I don't really know. Is their any similar or what is the approach for C++?

A: 

To give you some pointers for further investigation:

For a real C++ solution, you might want to look up stream and streaming operators like >>. CPP Reference is a good online API reference.

Still valid C++, but rooted in its C history would be the strtok() function to tokenize a string, which has several potential problems. As Martin correctly pointed out, it modifies the source data, which is not always possible. In addition there are problems with thread-safety and/or re-entrancy.

So usually you are a lot better of, using streams and C++ strings.

Steffen
stream iterator is a tad overkill for this situation. Unfortunately strtok() modifies the underlying data which is not a good thing.
Martin York
Hey, thanks, you are right of course. Actually I don't know, why I wrote 'iterator'... I'm sure I was thinking about operators :-)
Steffen
+7  A: 

The operator >> breaks a stream into words.
But does not detect end of line.

What you can do is read a line then get the first three words from that line:

#include <string>
#include <iostream>
#include <sstream>

int main()
{
    std::string line;
    // Read a line.
    // If it succeeds then loop is entered. So this loop will read a file.
    while(std::getline(std::cin,line))
    {
        std::string word1;
        std::string word2;
        std::string word3;

        // Get the first three words from the line.
        std::stringstream linestream(line);
        linestream >> word1 >> word2 >> word3;
    }

    // Expanding to show how to use with a normal string:
    // In a loop context.
    std::string       test("Hello stackoverflow is a really good site!");
    std::stringstream testStream(test);
    for(int loop=0;loop < 3;++loop)
    {
        std::string     word;
        testStream >> word;
        std::cout << "Got(" << word << ")\n";
    }

}
Martin York