gpt4 book ai didi

c++ - 为什么这个文件读不成功?

转载 作者:太空宇宙 更新时间:2023-11-04 13:02:10 26 4
gpt4 key购买 nike

我试图读入一个如下所示的 .dat 文件:

T001CD1              10000.00             2.5         2
T001CD2 50000.00 3.5 6
H407CD1 20000.00 2.0 1
M555CD1 30000.00 3.5 5
N423CD1 50000.00 3.0 4
N423CD2 60000.00 2.5 2
S602CD1 80000.00 4.0 8
H707CD1 25000.00 2.5 7

使用此代码:

void readCdAccountInfo()
{
ifstream in_stream;


in_stream.open("CdAccounts.dat");

while (!in_stream.eof())
{
int i = 0;
string iDTemp;
float ratetemp;
int yeartemp;
double depotemp;
while (in_stream
>> iDTemp
>> depotemp
>> ratetemp
>> yeartemp
)

{
CCdAccount temp(iDTemp, depotemp, ratetemp, yeartemp);
accounts[i] = temp;
i++;
}

{
if (in_stream.fail())
{
cout << "Input file opening failed. \n";
exit(1);
}

in_stream.close();
}}
}

ID、Deposit(私有(private)成员(member))、Rate 和 Year 都是我拥有的类(class)的一部分。

当我运行 main 时,唯一弹出的是输入文件失败消息。

最佳答案

首先,打开文件后立即检查打开错误。

ifstream in_stream("CdAccounts.dat");
if (in_stream.fail())
{
cout << "Input file opening failed. \n";
exit(1);
}

外循环 while (!in_stream.eof()) 已过时,因为您已经正确检查了内循环中的流错误。

在下面的代码中,我不知道变量accounts 的类型,但它看起来是一个数组。它与您遇到的问题没有直接关系,但如果文件包含的记录多于您为数组保留的记录,则该数组可能会溢出。我建议使用 std::vector相反,它会自动调整大小。

int i = 0;
string iDTemp;
float ratetemp;
int yeartemp;
double depotemp;

while (in_stream
>> iDTemp
>> depotemp
>> ratetemp
>> yeartemp
)
{
CCdAccount temp(iDTemp, depotemp, ratetemp, yeartemp);

// Instead of this...
accounts[i] = temp;
i++;

// ... I suggest declaring accounts as std::vector<CCdAccount>
// so you could add elements like this:
// accounts.push_back( temp );
}

下一个问题是在这段代码之后的错误检查。正如评论者彼得指出的那样:

Reaching end of file sets the eofbit for a stream. However, operations that attempt to read something (like operator>>()) also set the failbit if reaching end of file causes them to fail (i.e. to not receive input).

因此,为了仅检查意外 读取错误,我们必须从错误条件中排除 eof 位:

if (in_stream.fail() && ! in_stream.eof())
{
cout << "Input file reading failed.\n";
exit(1);
}

在函数结束时,无需显式close() 流,因为流的析构函数会在作用域结束时自动关闭文件。调用 close() 不是错误,它只是过时了。

关于c++ - 为什么这个文件读不成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43701512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com