gpt4 book ai didi

C++ 银行项目;如何从文件中读取字符串转换为 float 并求和

转载 作者:行者123 更新时间:2023-11-28 07:19:46 26 4
gpt4 key购买 nike

问题陈述:读取客户支票账户信息的 C++ 程序计算他/她的账户余额。应开发基于菜单的应用程序以迭代执行以下功能,直到用户请求退出程序:1. 显示,2. 存款,3. 取款,4. 退出。

这就是我目前所拥有的。

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

//Main function
int main()
{
//Identify type variables
int x=0;
float amountinput,famount,sum;
string firstname, lastname,date,filename,input,ID,amount;
fstream file;
//Program loop
while(true)
{
//Main menu loop
do
{

cout<<"Enter the number of the option you would like carried out.\n";
cout<<"1. Summary\n";
cout<<"2. Deposit\n";
cout<<"3. Withdraw\n";
cout<<"4. Quit\n";
cin>>x;
}
while(!x);

//When Quit is input, break
if(x==4)
{
break;
}
//Summary display
if (x==1)
{
cout<<"You have selected option number 1. Summary.\n"<<endl;
cout<<"Enter your Cust_ID: ";
cin>>ID;
file.open("C:\\Users\\Raggulddon\\Desktop\\C++ supplement
\\Cust_"+ID+".dat", ios::in|ios::out|ios::app);

//IF not found error.
if(!file)
{
cout<<"Sorry your account could not be found\n";
}
//Else display all content.
else
{
cout<<endl<<file.rdbuf()<<"\n";
file.close();

}
}
//Deposit
else if(x==2)
{
cout<<"You have selected option number 2. Deposit.\n";
cout<<"Please enter you account ID: ";
cin>>ID;
file.open("C:\\Users\\Raggulddon\\Desktop\\C++ supplement
\\Cust_"+ID+".dat", ios::in|ios::out|ios::app);

if(!file)
{
cout<<"Sorry the requested account could not be located.\n";
}
else
{
file>>firstname>>lastname;
cout<<endl<<firstname<<" "<<lastname<<endl;
while(!file.eof())
{
file>>date>>amount;
//
%%%%%%%%%%%%%%%%%%%//This is mainly where I am missing the lines of code..
//
float atof(string& amount);
cout<<date<<"\t\t"<<amount<<endl;
}


cin.get();cin.get();
cout<<"How much would you like to deposit today.";
cin>>amountinput;

cout<<endl;
file.close();

}
}

else if(x==3);
else if(x==4);


}
cin.get();cin.get(); //or system("PAUSE");
return 0;
}

示例文本文件如下所示,但行数不同。

James Bond
01/01/12 200010
03/30/12 -40000
04/30/12 -40000
05/30/12 -40000
06/30/12 -40000
07/30/12 -40000

我已设置 amount = string,然后我希望每个字符串彼此独立(以便我可以添加它们)并将它们转换为 float 或 double,以两者为准。

基本上,是这样的:

fstream file;
do
file>>date>>amount++; //I know this doesn't work, what will..
while(!file.eof());
float deposit;
finalAmount= deposit+amount;

最佳答案

C++ 输入运算符 >> 的好处在于它可以接受不同类型的参数,例如一个 double:

std::string date;
double amount;

file >> date >> amount;

但是,我更推荐使用 std::getlinestd::istringstream解析它:

std::string line;
std::getline(file, line);

std::istringstream iss(line)
iss >> date >> amount;

在某种程度上相关的注释中,不要使用while (!file.eof())eof 标志在实际输入操作失败之前不会被设置,因此除非您检查循环内的错误,否则您将尝试读取一次到多次。

而是做例如

while (std::getline(file, line))
{
...
}

关于C++ 银行项目;如何从文件中读取字符串转换为 float 并求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19676589/

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