I want to read then store the content of a file in an array, but this isn’t working:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string content,line,fname;
cout<<"Execute: ";
cin>>fname;
cin.ignore();
cout<<endl;
//Doesn't work:
ifstream myfile(fname);
if(!myfile.is_open()){
cout<<"Unable to open file"<<endl;
}else{
while(!myfile.eof()){
getline(myfile,line);
//I don't know how to insert the line in the string
}
myfile.close();
}
cin.get();
return 0;
}
2 things.
When creating your ifstream, you must pass a char*, but you’re passing a string. To fix this, write :
Also, to add the line to the content, call the “append” method :
It works for me 🙂
If you actually want to store each line seperatly, store every line into a string vector, like Skurmedel said.