Good evening dear colleagues,
I developed this program and I found out a problem. I created an array of objects, which contain a string inside each of them. Unfortunately I do not know how to write in those strings. What it shows is this: It allows me to write in this first object but not in the next ones! this is because the getline instruction was thought for files, not for the strings. I cannot also use cin or getchar because it stops at the first spacebar.
How can I settle this problem?
I can also use an array of char istead of a string, this is not the main point.
#include<iostream>
#include<string>
using namespace std;
const unsigned int MAXPROD = 10;
class Prodotto{
string descrizione;
float prezzo;
int numero_reparto;
public:
void registra(string , float, int);
void visualizza();
friend void elenco_per_reparto(int reparto, Prodotto prodotto[]);
Prodotto(): prezzo(0.0), numero_reparto(0) { descrizione= " ";}
};
void Prodotto:: registra( string s, float p, int n){
descrizione = s;
prezzo= p;
numero_reparto = n;
}
void Prodotto::visualizza(){
cout << descrizione << "," << prezzo << endl;
}
void elenco_per_reparto(int reparto, Prodotto prodotto[]){
for(int i = 0; i < MAXPROD; i++)
if(reparto == prodotto[i].numero_reparto)
prodotto[i].visualizza();
}
void inserisci_prodotti();
void lista_prodotti();
Prodotto prod[MAXPROD];
int main(){
int i;
inserisci_prodotti();
lista_prodotti();
cout << "digitare il numero del reparto: ";
cin >> i;
elenco_per_reparto(i, prod);
return 0;
}
void inserisci_prodotti(){
string descrizione_prodotti;
float prezzo_prodotti;
int np;
char risp;
for(int i = 0; i < MAXPROD;i++){
cout << "il prodotto " << i + 1 << endl;
do{
cout << "descrizione prodotto: ";
getline( cin, descrizione_prodotti); cout << "prezzo del prodotto: ";
cin >> prezzo_prodotti;
cout << "numero del reparto: ";
cin >> np;
prod[i].registra(descrizione_prodotti, prezzo_prodotti, np);
cout << "conferma? s/n";
cin >> risp;
}while(risp != 's');
}
}
void lista_prodotti(){
cout << "lista dei prodotti ";
for( int i = 0; i < MAXPROD; i++){
cout << "prodotto " << i + 1 << ":";
prod[i].visualizza();
}
}
What I have tried:
Good evening dear colleagues,
I developed this program and I found out a problem. I created an array of objects, which contain a string inside each of them. Unfortunately I do not know how to write in those strings. What it shows is this: It allows me to write in this first object but not in the next ones! this is because the getline instruction was thought for files, not for the strings. I cannot also use cin or getchar because it stops at the first spacebar.
How can I settle this problem?