Đọc nội dung file theo từng từ (word) trong C++ dùng fstream và toán tử >> (bỏ qua whitespace).
Thuật toán
read_word_by_word(filename):
file = open filename
while file has word:
read word
print word
close file
end
Nội dung file test (test_file.txt)
This is a test file. There are many words. The program will read this file word by word
Code ví dụ
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void readWordByWord(const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
cerr << "Khong the mo file: " << filename << endl;
return;
}
string word;
while (file >> word) { // Toán tử >> đọc một từ (bỏ qua whitespace)
cout << word << endl;
}
file.close();
}
int main() {
string filename;
cout << "Nhap ten file: ";
cin >> filename;
readWordByWord(filename);
return 0;
}
Kết quả
Nhap ten file: test_file.txt This is a test file. There are many words. The program will read this file word by word
Lưu ý quan trọng
file >> wordtách từ bằng whitespace (space, tab, newline).- Dấu câu (.,!?) được coi là một phần của từ.
- Để tách từ chính xác hơn (bỏ dấu câu), cần xử lý thêm.
Phiên bản nâng cao: Tách từ bỏ dấu câu
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
string cleanWord(string word) {
// Loại bỏ dấu câu ở đầu/cuối
while (!word.empty() && ispunct(word.front())) word.erase(0, 1);
while (!word.empty() && ispunct(word.back())) word.pop_back();
return word;
}
int main() {
ifstream file("test_file.txt");
string word;
while (file >> word) {
word = cleanWord(word);
if (!word.empty()) cout << word << endl;
}
return 0;
}
Đọc toàn dòng (getline)
string line;
while (getline(file, line)) {
// Xử lý từng dòng
stringstream ss(line);
string word;
while (ss >> word) { ... }
}