#include <iostream>
using namespace std;
class fruit{
private:
string name;
int amount;
float price;
public:
void getData(){
cout <<"Enter name of fruit: ";
cin.ignore();
getline(cin, name);
cout <<"Enter amount: ";
cin >>amount;
cout <<"Enter price: $";
cin >>price;
cout <<endl;
}
void displayData(){
cout <<"Fruit: " <<name <<endl;
cout <<"In stock: " <<amount <<endl;
cout <<"Price: $" <<price <<endl;
}
};
class seller{
public:
void display(fruit& obj){
cout <<"You are a seller!" <<endl <<endl;
obj.getData();
}
};
class buyer{
public:
void display(fruit& obj){
cout <<"You are a buyer!" <<endl <<endl;
obj.displayData();
}
};
int main(){
int userChoice;
cout <<"Welcome to shop simulator!" <<endl;
while(true){
cout <<"Please select anything from the following:" <<endl;
cout <<"[0] Exit the program" <<endl;
cout <<"[1] Seller" <<endl;
cout <<"[2] Buyer" <<endl;
cin >>userChoice;
fruit obj1;
seller obj2;
buyer obj3;
switch(userChoice){
case 0:
_Exit(0);
break;
case 1:
obj2.display(obj1);
break;
case 2:
obj3.display(obj1);
break;
}
}
}
Whenever I tried to enter a fruit and its properties in the buyer option and then tried to access it to the seller option, only the "amount" and "price" are being displayed. (I have tried using array of characters and it worked, but when I use string it doesn't work).
These three variables:
fruit obj1;
seller obj2;
buyer obj3;
are created from scratch everytime you loop. Hence the values you enter in iteration 1 are not preserved in the second iteration. The fact that you are getting price
and amount
correctly is just a coincidence.
To fix this quickly, just move the variables above outside the loop:
fruit obj1;
seller obj2;
buyer obj3;
cout <<"Welcome to shop simulator!" <<endl;
while(true){
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다