इस अनुभाग में हम देखेंगे कि C++ का उपयोग करके फाइल की सामग्री को शब्द दर शब्द कैसे पढ़ा जाए। कार्य बहुत सरल है। हमें फाइल इनपुट स्ट्रीम का उपयोग करके फाइल की सामग्री पढ़नी होगी। फाइल स्ट्रीम फाइल नाम का उपयोग करके फाइल खोलेगा, फिर FileStream का उपयोग करके प्रत्येक शब्द लोड करेगा और इसे word नामक वेरिएबल में स्टोर करेगा। फिर प्रत्येक शब्द को एक-एक करके प्रिंट करें।
एल्गोरिदम
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
फाइल सामग्री (test_file.txt)
This is a test file. There are many words. The program will read this file word by word
उदाहरण
#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) { //शब्द लें और प्रिंट करें
cout << word << endl;
}
file.close();
}
main() {
string name;
cout << "Enter filename: ";
cin >> name;
read_word_by_word(name);
}
आउटपुट
Enter filename: test_file.txt This is a test file. There are many words. The program will read this file word by word