gpt4 book ai didi

c++ - 从文件中读取 (C++)

转载 作者:行者123 更新时间:2023-11-30 04:34:36 25 4
gpt4 key购买 nike

我不明白为什么这不会从我的文件中读取...

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;

int main()
{
int acctNum;
int checks;
double interest;
double acctBal;
double monthlyFee;
const int COL_SZ = 3;
ifstream fileIn;
fileIn.open("BankAccounts.txt");
if(fileIn.fail())
{
cout << "File couldn't open." << endl;
}
else
{
cout << left;
cout << "Bank Account records:" << endl;
cout << setw(COL_SZ) << "Account#" << setw(COL_SZ) <<
"Balance" << setw(COL_SZ) << "Interest" << setw(COL_SZ) << "Monthly Fee" << setw(COL_SZ) <<
"Allowed Checks" << setw(COL_SZ) << endl;
while(fileIn >> acctNum >> acctBal >> interest >> monthlyFee >> checks)
{
cout << setw(COL_SZ) << acctNum << setw(COL_SZ) << acctBal << setw(COL_SZ) << interest << setw(COL_SZ) <<
monthlyFee << setw(COL_SZ) << checks << endl;
}
}
fileIn.close();
system("pause");
return 0;
}

我取出 ios::out 并放入 ios::in 同样的事情发生了,没有数据,同样的事情与将 ios 一起取出。 我确实从以前的程序制作了文件...我是否必须将读取文件的代码放入该程序中?

The BankAccount.txt file as a picture.

最佳答案

编辑

看看你的输入,你不能只用阅读如此复杂的输入

while(fileIn >> acctNum >> acctBal >> monthlyFee >> checks)

此代码设置为读取以下格式的数据:

11 12.12 11.11 13.13 14.1211 12.12 11.11 13.13 14.1211 12.12 11.11 13.13 14.12

Instead you'll have to read the various strings and such before scraping out the data you need. For example to skip over the word "Account" below, you can read it into a dummy string

Account Number#1234
 std::string dummy; 
fileIn >> dummy; // read up to the whitespace,
// in this case reads in the word "Account"

然后要获得数字,您必须读取下一个字符串并提取 #1234

 std::string temp; 
fileIn >> temp; // read up to the whitespace,
// in this case reads in the word "Number#1234"

但你也可以使用 getline阅读并包括 #

 std::getline(fileIn, dummy, '#');

然后读入#后面的数字

 int acctNum = 0;
fileIn >> acctNum;

因此,如果您输入的内容确实如您所描述的那样格式化,那么您将不得不花费比您预期更多的时间来弄清楚如何解析您的数据。我不太了解您的输入将如何为您提供完整的答案,但以上内容有望帮助您入门。

(可选,您可以学习正则表达式,但此时您可能只想学习基础知识。)

原创

我刚刚试用了您的代码,输入中有足够的格式正确的值,它可以在 g++ 中运行。但是,我对查看您的代码持谨慎态度的一件事是这一行:

   while(fileIn >> acctNum >> acctBal >> monthlyFee >> checks)

如果由于文件过早结束而无法读取上述任何内容,您的 cout 将不会被执行,从而导致屏幕上没有输出。您的输入是否具有以上所有值?它们格式正确吗?为了调试,我可能会尝试分解读取:

   while (fileIn)
{
fileIn >> acctNum;
std::cout << "Acct num is:" << acctNum << std::endl;
...
}

或者只是使用调试器逐步完成。

例如对于这个输入:

11 12.12 11.11 13.13 14.12

你的代码打印出来

Bank Account records:   Account#BalanceInterestMonthly FeeAllowed Checks   11 12.126.93517e-31011.1113 `

但是搞砸了输入并在某处添加了一个随机的非数字字符,即:

11 * 12.12 11.11 13.13 14.12

让我变得公正

Bank Account records:     Account#BalanceInterestMonthly FeeAllowed Checks

所以我肯定会逐个查看正在读取的内容以及从 fileIn 读取失败的位置,这肯定会导致您的问题。

您当然知道要删除指定的 ios::out here

关于c++ - 从文件中读取 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5864377/

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