C ++程序逐字读取文件?
在本节中,我们将看到如何使用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
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短