
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- C program to Replace a word in a text by another given word
- How to read Microsoft Word with Python?
- Java Program to set JTextArea to wrap by word in Java
- How to Convert an Excel File to a Word Document?
- How to reverse a given string word by word instead of letters using C#?
- Reading/Writing a MS Word file in PHP
- Python program to swap case of English word
- Python Program to Get word frequency in percentage
- C++ Program to Find number of Ways to Partition a word such that each word is a Palindrome
- ORDER BY a specific word in MySQL
- How to Count Word Occurrences in a Text File using Shell Script?
- How to grep and replace a word in a file on Linux?
- Golang program to read the content of a file line by line
- Number to word conversion
- Java program to reverse each word in a sentence

Advertisements