我的文件不工作并从 C++ 中的文件中读取上下文

My file is not working and reading the context from the file in C++

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

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

}

稍微更改了 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();
}