这里是我的代码:ifstream的是无法打开文件
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getHighScores(int scores[], string names[]);
int main()
{
ifstream stream;
stream.open("scores.txt");
int scores[32];
string names[32];
stream>>scores[0];
stream>>names[0];
if(stream.fail())
cout<<"It failed\n"<<strerror(errno)<<endl;
for(int i=1;i<5;i++)
{
stream>>scores[i];
stream>>names[i];
cout<<i<<endl;
}
cout<<scores[2]<<endl;
stream.close();
return 0;
}
void getHighScores(int scores[], string names[])
{
}
它得到的分数垃圾输出[2],因为stream.open(“scores.txt”)无法打开文件。 012rstrerror(errno)给我“没有错误”。
我检查过我的文件是否真的叫做“scores.txt.txt”。不是这样。我也尝试将我的文件移动到“C:\ scores.txt”。我试过使用完整的地址。我试过删除它并重新创建它。我尝试了其他我不记得的东西。 ![输入图像描述] [1]我一直在努力几个小时来解决这个问题,我很绝望。如果有人能帮我解决这个问题,我将不胜感激。
void gethighscores是我打算稍后使用的函数。
输入文件看起来是这样的:
Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000
程序的输出看起来像这样
It failed
No error
1
2
3
4
-858993460
Press any key to continue . . .
我在Microsoft Visual Studio Express的2012运行此为Windows桌面 我的工作系统是Windows 7的终极64位。
您确定您的[工作目录](http://en.wikipedia.org/wiki/Working_directory)中确实存在scores.txt?这不一定是可执行文件的路径。此外,试图直接从C:\打开文件可能会因其他原因(例如权限)失败。另外,在调用open(不仅在尝试读取之后)之后,您应该立即检查打开失败('stream.is_open()')。 – MooseBoys
它可能会帮助你很大程度上实际检查你的流提取的有效性,而不是盲目地假设他们的工作。此外,您输入文件的* real *样本以及您收到的* real *输出将与您正在运行的平台一起大大改善此问题。 – WhozCraig
@WhozCraig他尝试使用'“C:\ scores.txt”这个事实是对平台的一个很好的暗示。 –