IF流无法打开文件

ifstream is failing to open file

本文关键字:文件 IF      更新时间:2023-10-16

这是我的代码:

#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 failedn"<<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) 给我"没有错误"。

我已经检查了我的文件是否真的被称为"分数.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 . . .

我在 Visual Studio Express 2012 for Windows Desktop Microsoft运行它我的操作系统是Windows 7终极64位。

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

试试这个:

#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[])
{
}

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

颠倒scores.txt文件或C++解析代码中分数/名称的顺序(但不能两者兼而有之!),您应该很高兴。

它失败的原因是:

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

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

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

您将看到它不再失败并且工作正常。