gpt4 book ai didi

c++ - 如何将变量分配给 ASCII 文件中的项目并在 C++ 中计算它们?

转载 作者:行者123 更新时间:2023-11-30 05:40:31 25 4
gpt4 key购买 nike

我被告知要在包含以下信息的文本文件中列出一个列表:

Chisel 50 9.99  Hammer 30  15.99    Nails 2000 0.99
Bolts 200 2.99 Nuts 300 1.99 Soap 55 1.89

我写了这个程序来打开文件..但我不知道如何将像“凿子”这样的项目分配给程序中的变量,所以我可以用数量乘以价格来输出总价.

    cout << "----Make sure that the appropriate text file is located \nin the same directory as this program----" << endl;
cout << "\nNow enter the name of the text file, followed by " << ".txt" << endl;
string item;
int var1;
int var2;
int var3;
char filename[50];
ifstream wolf; //object name
cin.getline(filename, 50);
wolf.open(filename);

if (!wolf.is_open()){
exit(EXIT_FAILURE);
}
char word[50];
wolf >> word;
while (wolf.good()){
cout << word << " ";
wolf >> word;
}


while (wolf >> item >> var1 >> var2 >> var3)
{
cout << item << var1 << var2 << var3 << endl;
}
system("PAUSE");
return 0;
}

最佳答案

哥们下次认真使用delimiter,下面是可行但不是最优解的代码。此代码读取 text 文件并复制 item namechiselitem_name[20] array ,复制 quantity of item like 50qty 并且复制 rate of item like 9.99rate 然后通过计算你想要的qty*rate 来计算总价。这里使用了很多变量,请仔细观察。

#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;

struct List
{
char item_name[20];
int qty;
float rate;
}
List[20];

ifstream file;
int main()
{

int i,j,y,l,z,null;
l=j=0;z=-1;
char filename[10];
char line[80];char number[21];

for(y=0;y<80;y++)
{
line[y]=NULL;
}
cout<<"Enter file name : ";
cin>>filename;
file.open(filename,ios::in);
if(!file)
{
cerr<<"File does not exist !!!";
exit(0);
}
while(file.getline(line,80))
{
z=z+1;j=0;
i=strlen(line);
for(y=0;y<i;y++)
{
if(isalpha(line[y]))
{ List[z].item_name[j]=line[y];j=j+1;}
if(line[y]==' ')
{
for(null=0;null<=20;null++)
{
number[null]=NULL;
}
if(isalpha(line[y-1]))
{
l=1;j=0;
}
if(isdigit(line[y-1]))
{
l=2;j=0;
}
if(isalpha(line[y+1]))
{
z=z+1;
}
}
if(isdigit(line[y])||(line[y]=='.'))
{
number[j]=line[y];
if(l==1)
{
List[z].qty=atoi(number);
}
if((l==2)||(line[y]=='.'))
{
List[z].rate=atof(number);
}
j=j+1;
}
}
}
file.close();

for(y=0;y<=z;y++)
{
//cout<<List[y].item_name<<" "<<List[y].qty<<" "<<List[y].rate<<endl;
cout<<"Name of item : "<<List[y].item_name<<" Qty of this item : "<<List[y].qty<<" Rate of this item : "<<List[y].rate;
cout<<"\nPrice = Qty of item * Rate of this item = "<<List[y].qty*List[y].rate<<endl;
}
return 0;
}

关于c++ - 如何将变量分配给 ASCII 文件中的项目并在 C++ 中计算它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31595054/

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