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

I am trying to read a file line by line of a variable of type string 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 will not compile when I try to use the String class, only when I use char file[256] .

How can I get line by line in a string class?

+4
source share
1 answer

Use std::getline :

 std::string s; while (std::getline(file, s)) { // ... } 
+10
source

Source: https://habr.com/ru/post/1306069/


All Articles