Spliting text into separate words

Discussion in 'C++' started by Virgo, Jan 27, 2004.

  1. Virgo

    Virgo Guest

    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);
     
    Virgo, Jan 27, 2004
    #1
    1. Advertisements



  2. 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.
     
    Karl Heinz Buchegger, Jan 27, 2004
    #2
    1. Advertisements

  3. Virgo

    Attila Feher Guest

    [SNIP]

    Homework?
     
    Attila Feher, Jan 27, 2004
    #3
  4. 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.
     
    Karl Heinz Buchegger, Jan 27, 2004
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.