C++ program to read file word by word

Given a text file, extract words from it. In other words, read the content of file word by word.
Example :

Input: And in that dream, we were flying.
Output:
And
in
that
dream,
we
were
flying.

Approach :



1) Open the file which contains string. For example, file named “file.txt” contains a string “geeks for geeks”.
2) Create a filestream variable to store file content.
3) Extract and print words from the file stream into a string variable via while loop.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to read
// file word by word
#include <bits/stdc++.h>
using namespace std;
  
// driver code
int main()
{
    // filestream variable file
    fstream file;
    string word, t, q, filename;
  
    // filename of the file
    filename = "file.txt";
  
    // opening file
    file.open(filename.c_str());
  
    // extracting words from the file
    while (file >> word)
    {
        // displaying content
        cout << word << endl;
    }
  
    return 0;
}

chevron_right


Output:

geeks
for
geeks.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : imim123345667899



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.