Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file line by line to a string type variable?

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?

like image 869
ufk Avatar asked Apr 05 '10 23:04

ufk


People also ask

How do I read a file to string?

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.

How do I read the contents of a file line by line?

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.

Which method is used to read file line by line?

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.


1 Answers

Use std::getline:

std::string s;
while (std::getline(file, s))
{
    // ...
}
like image 173
James McNellis Avatar answered Oct 02 '22 16:10

James McNellis