Spliting text into separate words

V

Virgo

The code below cout's separate words from file "text.txt".

int main() {
vector<string> words;
ifstream in("text.txt");
string word;
while(in >> word)
words.push_back(word);
for(int i = 0; i < words.size(); i++)
cout << words << endl;
}

Question?

What I should change in this code above if I like split sentence
entered from keyboard.

string s;
getline(cin,s);
 
K

Karl Heinz Buchegger

Virgo said:
The code below cout's separate words from file "text.txt".

int main() {
vector<string> words;
ifstream in("text.txt");
string word;
while(in >> word)
words.push_back(word);
for(int i = 0; i < words.size(); i++)
cout << words << endl;
}

Question?

What I should change in this code above if I like split sentence
entered from keyboard.


In your program 'in' is a stream object which is connected to a file.
Another stream object you can use is cin. But the important point
is: both are stream objects and work the same way.
Thus you can do:

string word;

while( cin >> word )
words.push_back( word );

You simply replace one stream object with the other stream object.
 
K

Karl Heinz Buchegger

Attila said:
The code below cout's separate words from file "text.txt".
[SNIP]

Homework?

Don't think so.
Usually people have the problem the other way round: I can do it
with cin, but how to do it with a file stream?

Sounds more like a language hopper working through a tutorial
on the Web, but since he already knows another language he has skipped
the first chapters.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top