0

my partner wrote a bunch of code for one of my projects in a text editor, when i run the code it works perfectly..... now i have copy and pasted all the code into qt creator, and im having an issue

 stringstream ss;
            string line;
            ifstream myfile;
            myfile.open("Instructors.txt");
            if (myfile.is_open()){
                while (getline(myfile,line)){
                    ss << line << ", ";
                }
                myfile.close();
            }
            else cout << "bad open" << endl;

above is the part fo my code that is having the issue, i can assure you all Instructors.txt is indeed in in the correct file, but everytime our code reaches this point imstead of opening the file i get thrown to the else "bad open" why would this be?

4

3 回答 3

1

很难说没有任何错误代码可能是什么,您可以做的是用更有意义的东西(对您和您的客户)改进您的错误消息:

else cout << "Error opening file: " << strerror(errno) << endl;

strerror(请参阅参考资料errno)函数返回宏捕获的给定错误代码的字符串。

否则,您可以使用异常来做更多的 C++ish:首先为您的流启用它们:

myfile.exceptions(ifstream::failbit | ifstream::badbit);

然后抓住他们,一起就是:

try
{
    ifstream myfile("Instructors.txt");
    myfile.exceptions(ifstream::failbit | ifstream::badbit);

    while (getline(myfile, line))
    {
        ss << line << ", ";
    }

    myfile.close();
}
catch (ifstream::failure e)
{
    cout << e.what() << endl;
}
于 2013-11-05T10:36:59.203 回答
0

尝试重写文件名,可能它包含来自不同编码的字符。

于 2013-11-05T10:44:03.213 回答
0

仔细检查工作目录,它可能在构建文件夹中(可执行文件被删除的地方)

在 QtCreator 中,您可以通过转到项目并选择运行来解决此问题;在那里你将能够设置工作目录

于 2013-11-05T11:05:58.060 回答