我的文件无法正常工作,正在使用C ++

时间:2018-10-05 18:42:23

标签: c++ string file fstream ifstream

我试图打开某个文件并读取内容,将其放入名为字母的字符串中,但是每次我键入文件名时,我一直收到错误消息,找不到打开的文件。

void createTree() {

BTS tree;
string filename;
string letters;
ifstream file;
int input = 0;

cout<<"Enter the file name:  ";     // ask the user to input the file name
cin >>filename; //input the user input into filename

file.open(filename.c_str());
if(file)
{
    cout<<"File is open";
    while(!file.eof())
    {
        cout<< "In the while loop"<<endl;
        getline(file, letters);
        tree.insertWord(letters);
    }
}

else
      cout<<"Error can't open the file"<<endl;
tree.printTree();

file.close();

}

1 个答案:

答案 0 :(得分:1)

稍微更改了getline调用,看看是否可行:

void createTree()
{
    BTS tree;
    string filename;
    string letters;
    ifstream file;
    int input = 0;

    cout<<"Enter the file name:  ";     // ask the user to input the file name
    cin >>filename; //input the user input into filename

    file.open(filename.c_str());
    if(file)
    {
        cout<<"File is open" << endl;
        ifstream file(filename.c_str());
        char chars[100];

        while (!file.eof()) {
            file.getline(chars, 100);
            tree.insertWord(letters);
            letters = chars;
            cout << letters << endl;
        }
    } else {
        cout<<"Error can't open the file"<<endl;
    }
    tree.printTree();

    file.close();
}