I'm trying to read a file line by line to a string type variable using the following code:
#include <iostream>
#include <fstream>
ifstream file(file_name);
if (!file) {
cout << "unable to open file";
exit(1);
}
string line;
while (!file.eof()) {
file.getline(line,256);
cout<<line;
}
file.close();
it won't compile when I try to use String class, only when I use char file[256]
instead.
how can I get line by line into a string class?
The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.
Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.
We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.
Use std::getline
:
std::string s;
while (std::getline(file, s))
{
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With