so I've been doing my homework and I stumbled upon a problem. After I input part of the date for my program it just goes into an infinite loop. The idea is to create an array that consists of structure entries. I'm not sure where the problem seems to be coming from since it just starts printing out "Your choice: " without stopping. Here is my code:
#include <iostream>
using namespace std;
struct property {
int num;
char nBrok[50];
char type[10];
char adress[50];
char outlook[20];
double price;
double size;
int nRooms;
int floor;
char status[2];
};
int menu() {
int ch;
cout<<"Choose an option from 1-5."<<endl;
cout<<"1. Add property."<<endl;
cout<<"2."<<endl;
cout<<"3."<<endl;
cout<<"4."<<endl;
cout<<"5. Exit"<<endl;
do {
cout << "\nYour Choice: ";
cin>>ch;
} while (ch<1 || ch>5);
return ch;
}
void addProp(property bDanni[]) {
int count;
cout<<"1. Add property."<<endl;
cout<<"How many real estate properties would you like to add?"<<endl;
cin>>count;
for(int i=0; i < count; i++)
{
cin.ignore();
cout<<"Enter the entry number of the property: "; cin>>bDanni[i].num;
cout<<"Enter the name of the property's broker: "; cin.getline(bDanni[i].nBrok, 50);
cin.ignore();
cout<<"Enter the type of the property: "; cin.getline(bDanni[i].type, 10);
cin.ignore();
cout<<"Enter the adress of the property: "; cin.getline(bDanni[i].adress, 50);
cin.ignore();
cout<<"Enter the outlook of the property: "; cin.getline(bDanni[i].outlook, 20);
cin.ignore();
cout<<"Enter the price of the property: "; cin>>bDanni[i].price;
cout<<"Enter the size of the property: "; cin>>bDanni[i].size;
cout<<"Enter the number of rooms of the property: "; cin>>bDanni[i].nRooms;
cout<<"Enter the floor of the property: "; cin>>bDanni[i].floor;
cout<<"Enter the status the property: "; cin.getline(bDanni[i].status, 2);
cin.ignore();
}
}
int main() {
property bDanni[100];
int choice;
do {
choice = menu();
switch (choice) {
case 1: addProp(bDanni);break;
}
}while (choice !=5);
return 0;
}
Use cin.ignore() when you are about to use getline after using cin. Because cin leaves the null character in the buffer.