C++ program to read file word by word?


In this section we will see how we can read file content word by word using C++. The task is very simple. we have to use the file input stream to read file contents. The file stream will open the file by using file name, then using FileStream, load each word and store it into a variable called word. Then print each word one by one.

Algorithm

read_word_by_word(filename)

begin
   file = open file using filename
   while file has new word, do
      print the word into the console
   done
end

File Content (test_file.txt)

This is a test file. There are many words. The program will read this file word by word

Example

#include<iostream>
#include<fstream>
using namespace std;
void read_word_by_word(string filename) {
   fstream file;
   string word;
   file.open(filename.c_str());
   while(file > word) { //take word and print
      cout << word << endl;
   }
   file.close();
}
main() {
   string name;
   cout << "Enter filename: ";
   cin >> name;
   read_word_by_word(name);
}

Output

Enter filename: test_file.txt
This
is
a
test
file.
There
are
many
words.
The
program
will
read
this
file
word
by
word
raja
Published on 25-Jul-2019 13:32:24
Advertisements