Open In App
Related Articles

C++ program to read file word by word

Improve Article
Improve
Save Article
Save
Like Article
Like

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. 

CPP




// 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;
}


Output:

geeks
for
geeks.

Time Complexity: O(N) // going through the entire file

Auxiliary Space: O(1)

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 14 Feb, 2023
Like Article
Save Article
Similar Reads