इस खंड में हम देखेंगे कि कैसे हम C++ का उपयोग करके फ़ाइल सामग्री को शब्द दर शब्द पढ़ सकते हैं। कार्य बहुत सरल है। फ़ाइल सामग्री को पढ़ने के लिए हमें फ़ाइल इनपुट स्ट्रीम का उपयोग करना होगा। फ़ाइल स्ट्रीम फ़ाइल नाम का उपयोग करके फ़ाइल खोलेगी, फिर फ़ाइलस्ट्रीम का उपयोग करके, प्रत्येक शब्द को लोड करें और इसे शब्द नामक एक चर में संग्रहीत करें। फिर प्रत्येक शब्द को एक-एक करके प्रिंट करें।
एल्गोरिदम
read_word_by_word(फ़ाइल नाम)
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) { //take word and print 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