开发者

Simple C++ File stream

开发者 https://www.devze.com 2022-12-14 23:27 出处:网络
I want to read then store the content of a file in an array, but this isn\'t working: #include <iostream>

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;开发者_StackOverflow社区
    //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 :

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.


replace

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

with

   char c;    
   while(myfile.get(c))
   {
        line.push_back(c);
   }


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()).

0

精彩评论

暂无评论...
验证码 换一张
取 消