ในส่วนนี้เราจะดูวิธีอ่านเนื้อหาไฟล์ทีละคำโดยใช้ C++ งานนี้ง่ายมาก เราต้องใช้ file input stream เพื่ออ่านเนื้อหาไฟล์ file stream จะเปิดไฟล์ด้วยชื่อไฟล์ จากนั้นใช้ 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) { // take word and print
cout << word << endl;
}
file.close();
}
int 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