Reputation: 8551
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++?
Upvotes: 1
Views: 1562
Reputation: 1401
This is easy and 100% reliable
void Split(std::string script)
{
std::string singelcommand;
std::stringstream foostream(script);
while(std::getline(foostream,singelcommand))
show_remote_processes(_ssh_session,singelcommand);
}
Upvotes: 0
Reputation: 2948
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.
Upvotes: 0
Reputation: 264571
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";
}
}
Upvotes: 7