逐字讀取檔案的 C++ 程式?
在本節中,我們將看到如何使用 C++ 逐字讀取檔案內容。這個任務很簡單。我們必須使用檔案輸入流來讀取檔案內容。檔案流將使用檔名開啟檔案,然後使用 FileStream 載入每個單詞並將它們儲存到一個名為單詞的變數中。然後逐個列印每個單詞。
演算法
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(); } 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
廣告