이 섹션에서는 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