在 qt 中使用 ifstream 打开文件时出现问题
Issue opening file with ifstream in qt
我的搭档在文本编辑器中为我的一个项目写了一堆代码,当我运行代码时,它运行得很好......现在我已经将所有代码复制并粘贴到Qt Creator中,我遇到了一个问题
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;
以上是我的代码出现问题的部分,我可以向所有讲师保证.txt确实在正确的文件中,但是每次我们的代码达到打开文件的这一点时,我都会被扔到其他"糟糕的打开"为什么会这样?
如果没有任何错误代码,很难说它可能是什么,您可以做的是用更有意义的东西(对您和您的客户)来改进您的错误消息:
else cout << "Error opening file: " << strerror(errno) << endl;
strerror
(请参阅参考)函数返回宏捕获的给定错误代码errno
字符串。
否则,您可以使用异常来C++:首先为您的流启用它们:
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;
}
尝试重写文件名,可能是它包含来自不同编码的字符。
仔细检查工作目录,很可能它在构建文件夹中(可执行文件被删除的地方)
在QtCreator中,您可以通过转到项目并选择运行来解决此问题;在那里您将能够设置工作目录
相关文章:
- 使用mongocxx驱动程序时包含头文件问题
- 生成文件问题
- 从文件问题加载纹理 Android NDK 和 OpenGL
- Xcode 11 头文件问题
- 使用 c++ ifstream 读取文本文件问题
- 单独的类声明和方法定义文件问题
- C++生成文件问题
- 生成文件问题(体系结构x86_64的未定义符号:"_main",引用自:主可执行文件的隐式入口/启动)
- C++删除未使用的库的生成文件问题
- C++ 使文件问题
- 阅读矩阵市场文件C++问题
- 查找第一个文件问题无法使任何示例正常工作。
- "Recursive Makefile Considered Harmful"样式生成文件问题
- 标题文件问题中的类定义
- 嵌套 while 循环,包含文件 c++ 问题
- 几个制作文件问题
- 生成文件问题,获取"目标'rgbapixel.o'的配方失败"
- 从yaml文件问题opencv读取数据
- 类成员C++标头和 .cc 文件问题
- 添加选项以显示百分比时出现生成文件问题