ในส่วนนี้เราจะมาดูกันว่าเราสามารถอ่านเนื้อหาไฟล์แบบคำต่อคำโดยใช้ C++ ได้อย่างไร งานนี้ง่ายมาก เราต้องใช้สตรีมอินพุตไฟล์เพื่ออ่านเนื้อหาไฟล์ สตรีมไฟล์จะเปิดไฟล์โดยใช้ชื่อไฟล์ จากนั้นใช้ FileStream โหลดแต่ละคำและจัดเก็บไว้ในตัวแปรที่เรียกว่า word แล้วพิมพ์ทีละคำ
อัลกอริทึม
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