Reading and Processing a File Line by Line in C++
Posted on In QAIn 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.
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.
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";
}
}
You’re adding an ‘n’ character after every line instead of newline.
but Why you the loop is not accessible after using it i want the loop to be accessible every time not only one time plz
file
is a stream. You need to dofile.seekg(0);
if you want to read the file content again.How do i get a string of text from a file then compare it?