我想读取然后将文件的内容存储在数组中,但这不起作用:
#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;
}
Run Code Online (Sandbox Code Playgroud)
2件事.创建ifstream时,必须传递char*,但是传递的是字符串.要解决这个问题,请写:
ifstream myfile(fname.c_str());
Run Code Online (Sandbox Code Playgroud)
另外,要将内容添加到内容中,请调用"append"方法:
content.append(line);
Run Code Online (Sandbox Code Playgroud)
这个对我有用 :)
如果你真的想要分别存储每一行,将每一行存储到一个字符串向量中,就像Skurmedel说的那样.