ifstream无法打开文件

时间:2013-12-18 18:26:08

标签: c++ 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”)无法打开文件。 strerror(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 for Windows Desktop中运行此功能 我的操作系统是Windows 7 ultimate 64 bit。

4 个答案:

答案 0 :(得分:2)

试试这个:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getHighScores(int scores[], string names[]);

int main()
{
    string filename = "scores.txt"; // could come from command line.
    ifstream fin(filename.c_str());
    if (!fin.is_open())
    {
        cout << "Could not open file: " << filename << endl;
        return 1;
    }

    int scores[32];
    string names[32];

    int iter = 0;
    while (fin >> names[iter] >> scores[iter])
    {
        if (++iter >= 32 )
        {
            break;
        }
        cout << iter << endl;
    }

    if (iter >= 2)
    {
        cout << scores[2] << endl;
    }

    fin.close();

    return 0;
}

void getHighScores(int scores[], string names[])
{

}

答案 1 :(得分:1)

使用“\”来定义路径时,使用两个而不是一个 C:\\ scores.txt

答案 2 :(得分:1)

让我难过了一下。您的C ++代码以与输入文本相反的顺序读取分数和名称。输入文件中的第一行文本为Ronaldo,但您的第一行operator>>score[0]int)。这会导致设置failbit,因此fail()会返回true。它还解释了为什么最终会为目标数组元素获取垃圾。

scores.txt文件或C ++解析代码中反转得分/名称的顺序(但不是两者都有!),你应该好好去。

答案 3 :(得分:0)

失败的原因是:

int scores[32];
string names[32];
stream>>scores[0];
stream>>names[0];
if(stream.fail())
    cout<<"It failed\n"<<strerror(errno)<<endl; 

默认情况下,score [0]和names [0]没有任何设置值,它会尝试将它们分配给文件,这会导致它失败。如果您尝试评论这两行:

stream>>scores[0];
stream>>names[0];

你会发现它不再失败并且工作正常。

相关问题