need help with char operator

In the following program:, the output does not give distinct names of items entered by me. whenever I select display option the column of item name will just display same name in all rows (the name that i entered the last), I want those names to be displayed that were entered earlier by me. please run the program if required for better acknowledgement of my issue.

#include<iostream>
using namespace std;
int n;
class shop
{

public:
int item_code[100]={};
char i_name[20]={};
float price[100]={0.0};
float total=0.0;
void add_item()
{
int i;
cout<<"enter the no. of items you want to purchase"<<endl;
cin>>n;
for(i=0;i<n;i++)
{
cout<<"enter the ITEM CODE for item you wish to add"<<endl;
cin>>item_code[i];
cout<<"enter the NAME of the item"<<endl;
cin>>i_name;
cout<<"enter PRICE for the item"<<endl;
cin>>price[i];
}
}
void Total()
{
cout<<"--------------------------------------------------"<<endl;
for(int i=0;i<n;i++)
{
total=total+price[i];
}
cout<<"TOTAL: \t \t \t \t "<<total<<endl;
cout<<"--------------------------------------------------"<<endl;
}
void display()
{
for(int i=0;i<n;i++)
{
cout<<item_code[i]<<"\t \t "<<i_name<<"\t \t "<<price[i]<<endl;
}
Total();
}
};
int main()
{
int i,n;
shop s[100];
int ch;
while(true)
{
cout<<"\n 1.add item to your cart \n 2.display items"<<endl;
cout<<"enter your choice"<<endl;
cin>>ch;
switch(ch)
{
case 1: s[i].add_item();break;
case 2: cout<<"-------------------THE SALE------------------"<<endl;
cout<<"item_code \t item_name \t price"<<endl;
for(i=0;i<n;i++)
{
s[i].display();break;
}break;
default:cout<<"invalid choice!!"<<endl;
break;
}

}
}
Last edited on
1
2
3
4
5
6
7
8
char i_name[20]={};
...
for(i=0;i<n;i++)
{
...
cout<<"enter the NAME of the item"<<endl;
cin>>i_name;
}


You read all names into the same variable thus overriding the previous ones. You need to use an array for all the names like you use for price and item_code.
Topic archived. No new replies allowed.