tags:

views:

167

answers:

3

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  A: 

replace

while(!myfile.eof()){
     getline(myfile,line);
}

with

   char c;    
   while(myfile.get(c))
   {
     line.push_back(c);
   }
DanDan
Although reading the file char by char is not great, you seem to be the only one who knows how (not) to use `eof` correctly. +1
avakar
+6  A: 

2 things. When creating your ifstream, you must pass a char*, but you're passing a string. To fix this, write :

ifstream myfile(fname.c_str());

Also, to add the line to the content, call the "append" method :

content.append(line);

It works for me :)

If you actually want to store each line seperatly, store every line into a string vector, like Skurmedel said.

Jesse Emond
The append method doesn't make the line break :(
M28
Nevermind, I just added +"\n"
M28
Oh well. I didn't test the code with more than one line in the file, my bad ;)
Jesse Emond
+2  A: 

So you're trying to read the contents of a file into one string, or you want each line to be an array entry?

If the former, after you call getline() you will need to append the line (+= is a shortcut for append) content += line;.

If the latter, create a vector of strings and call content.push_back(line).

Strings have a .c_str() method which returns a char array, so you probably need to call ifstream myfile(fname.c_str()).

Ephphatha