read words from inoput, store in a file

Hi! How kan I write a program that reads words from the user input (cin), and stores each word as a separate line in a text file.

I guess I need a cout << "write some words"; and then the user writes some words. But how do I manage to store each line in a text file?
You can get the line, then divide it in words and write those words to the file followed by a newline character

eg:
1
2
3
4
5
6
7
8
9
10
string line;
getline(cin,line);//get a line
istringstream ss(line);//create a stream with that line
string word;
while(true)
{
	ss >> word;//get a word from the stream
	if(ss.eof()) break;//stop if there aren't more words
	YourFile << word << '\n';//store the word in the file        
}
Last edited on
Thanks! That maked sense :)

if I want to store the input in a string instead and use a
specific word to terminate the input process such as "quit". And then
use the compare method of the string class to test if the temination word
is found (this function will return 0 if the strings are equal)., how do I do that?

What is the compare method?
Last edited on
you can use string::find
eg:
1
2
3
4
string line;
getline(cin,line);
if ( line.find( "quit" ) != string::npos )
   //The string contains "quit" 

http://www.cplusplus.com/reference/string/string/find.html
Topic archived. No new replies allowed.