简单的C ++文件流

时间:2009-12-20 22:40:12

标签: c++ file stream

我想读取然后将文件的内容存储在数组中,但这不起作用:

#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;
}

3 个答案:

答案 0 :(得分:7)

2件事。 创建ifstream时,必须传递char *,但是传递的是字符串。要解决此问题,请写下:

ifstream myfile(fname.c_str());

此外,要将内容添加到内容中,请调用“append”方法:

content.append(line);

它对我有用:)

如果你真的想要分别存储每一行​​,请将每一行存储到一个字符串向量中,就像Skurmedel所说。

答案 1 :(得分:2)

替换

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

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

答案 2 :(得分:2)

所以你试图将文件的内容读入一个字符串,或者你希望每一行都是一个数组条目?

如果是前者,则在致电getline()后,您需要附加该行(+=是追加的快捷方式)content += line;

如果是后者,请创建一个字符串向量并调用content.push_back(line)

字符串有一个返回char数组的.c_str()方法,所以你可能需要调用ifstream myfile(fname.c_str())