How to read a file and get words in C++

前端 未结 4 986
温柔的废话
温柔的废话 2021-01-16 02:06

I am curious as to how I would go about reading the input from a text file with no set structure (Such as notes or a small report) word by word. The text for example might b

4条回答
  •  再見小時候
    2021-01-16 02:44

    Since it's easier to write than to find the duplicate question,

    #include 
    
    std::istream_iterator word_iter( my_file_stream ), word_iter_end;
    
    size_t wordcnt;
    for ( ; word_iter != word_iter_end; ++ word_iter ) {
        std::cout << "word " << wordcnt << ": " << * word_iter << '\n';
    }
    

    The std::string argument to istream_iterator tells it to return a string when you do *word_iter. Every time the iterator is incremented, it grabs another word from its stream.

    If you have multiple iterators on the same stream at the same time, you can choose between data types to extract. However, in that case it may be easier just to use >> directly. The advantage of an iterator is that it can plug into the generic functions in .

提交回复
热议问题