c语言读取文件逐行处理
In C++, how to process a file line by line? The file is a plain text line like input.txt. As an example, the process can be to just print it out.
在C ++中 ,如何逐行处理文件? 该文件是纯文本行,例如input.txt。 例如,该过程可以只是将其打印出来。
In C++, you may open a input stream on the file and use the std::getline()
function from the <string>
to read content line by line into a std::string
and process them.
在C ++中 ,您可以打开文件上的输入流,并使用< string >
的std::getline()
函数将内容逐行读取到std::string
并进行处理。
std::ifstream file("input.txt");
std::string str;
while (std::getline(file, str)) {
// process string ...
}
A full example is as follows:
完整的示例如下:
$ g++ file-read-line.cpp -o s && ./s
$ cp file-read-line.cpp input.txt
$ ./s
#include <iostream>
#include <fstream>
#include <string>
int main ()
{
std::ifstream file("input.txt");
std::string str;
while (std::getline(file, str)) {
std::cout << str << "\n";
}
}
Answered by dtivl.
dtivl回答。
翻译自: https://www.systutorials.com/how-to-process-a-file-line-by-line-in-c/
c语言读取文件逐行处理