我被告知在文本文件中有一个包含以下信息的列表:
Chisel 50 9.99 Hammer 30 15.99 Nails 2000 0.99
Bolts 200 2.99 Nuts 300 1.99 Soap 55 1.89
我已经编写了这个程序打开文件..我不知道如何将“chisel”这样的项目分配给程序中的变量,所以我可以将数量乘以价格来输出总价格
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;
}
答案 0 :(得分:1)
Dude下次认真使用delimiter
,下面是可行解决但不是最优的代码。此代码读取text
文件并将item name
复制为chisel
到item_name[20]
数组,将quantity of item
复制为50
到qty
并将rate of item
9.99
复制到rate
,然后通过计算您想要的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;
}