reading words from input...

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
midra
Experienced poster
Posts: 119
Joined: Fri Feb 13, 2004 7:20 am
Contact:

reading words from input...

Post by midra »

Hi...
I need help to do the following:
I want to take from standard input a line like this
" word1 word2 word3 wordn" and get all the words in differents strings (strings from <string> of course)
does someone know an easy way to do it??
is it any other way (easier) to manage the words in an input like this???

thanks!
sohel
Guru
Posts: 856
Joined: Thu Jan 30, 2003 5:50 am
Location: New York

Post by sohel »

I think you are looking for stringstream.
jan_holmes
Experienced poster
Posts: 136
Joined: Fri Apr 15, 2005 3:47 pm
Location: Singapore
Contact:

Post by jan_holmes »

The easy implementation of stringstream is like this :

Code: Select all

vector< string > str;
string s = "word1 word2 word3";
string p;
istringstream ss(s);
while (ss >> p) str.push_back(p);
Hope it helps :wink: [/code]
midra
Experienced poster
Posts: 119
Joined: Fri Feb 13, 2004 7:20 am
Contact:

Post by midra »

thanks for your reply...
but how can I know when a line ends...
I mean, if in the input I have this:
"word1 word2 word3
word4 word5 word6 word7"
I want to make something whit word1 word2 and word3, and then do it again with word4, word5, word6 and word7
If I make like you say with stringstream I think I would not distinguish what words are from the first line and what are from the second
mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Post by mf »

Use getline() to read input line-by-line, and stringstream to split each line into words. Code:

Code: Select all

string line, word;
while (getline(cin, line)) {  // reads next line until EOF
    istringstream tokenizer(line);
    while (tokenizer >> word) {
        // do something with this word
    }
}
midra
Experienced poster
Posts: 119
Joined: Fri Feb 13, 2004 7:20 am
Contact:

Post by midra »

thank you!!!
and I don't want to be annoying but I have just one more question
how can I distinguish between a new line in an input like this:
"w1 w2 w3
w4 w5 w6 w7

ww1 ww2 ww3
ww4 ww5 ww6 ww7"

In case that this represents different tests.
I mean, I need to know when a newLine alone appears so the next to read is from a different test (I have seen a lot of problems with input like this)
thanks again!!
jan_holmes
Experienced poster
Posts: 136
Joined: Fri Apr 15, 2005 3:47 pm
Location: Singapore
Contact:

Post by jan_holmes »

you can use something like :

Code: Select all

if (line.length() == 0) // do something
midra
Experienced poster
Posts: 119
Joined: Fri Feb 13, 2004 7:20 am
Contact:

Post by midra »

thank you so much!!!!! :D :D :D
Post Reply

Return to “C++”