This question already has an answer here:
earlier i posted a question about cin
skipping input, and I got results to flush, and use istringstream
, but now I tried every possible solution but none of them work.
here is my code:
void createNewCustomer () {
string name, address;
cout << "Creating a new customer..." << endl;
cout << "Enter the customer's name: "; getline(cin, name);
cout << "Enter the customer's address: "; getline(cin, address);
Customer c(name, address, 0);
CustomerDB::addCustomer(c);
cout << endl;
}
but I'm still getting the same thing, skipping input, and when it does take input, it takes them and stores in name empty nothing, and in address it takes what i wrote in name but from the 2nd letter to the end
what is wrong with my code?
I tried the cin.ignore()
, cin.get()
, and cin.clear()
all of them together and alone, none of them worked
EDIT:
main method in main.cpp invokes mainMenu()
only
void mainMenu () {
char choice;
do {
system("cls");
mainMenuDisplay();
cin >> choice;
system("cls");
switch (choice) {
case '1':
customerMenu();
break;
case '2':
dvdMenu();
break;
case '3':
receiptMenu();
break;
case '4':
outro();
break;
default:
cout << '\a';
}
cin.ignore();
cin.get();
} while (choice != '4');
}
i will choose 1 for the customer example, this is customerMenu()
void customerMenu () {
char choice;
do {
system("cls");
manageCustomerMenu();
cin >> choice;
system("cls");
switch (choice) {
case '1':
createNewCustomer();
break;
case '2':
deleteCustomer();
break;
case '3':
updateCustomerStatus();
break;
case '4':
viewCustomersList();
break;
case '5':
mainMenu();
break;
default:
cout << '\a';
}
cin.ignore();
cin.get();
} while (choice != '5');
}
I choose 1 again to create a new customer object, which will now go to the MainFunctions.cpp which will invoke the function createNewCustomer()
which is the first one.
void createNewCustomer () {
string name, address;
cout << "Creating a new customer..." << endl;
cout << "Enter the customer's name: "; cin.getline(name,256);
cout << "Enter the customer's address: "; cin.getline(address,256);
Customer c(name, address, 0);
CustomerDB::addCustomer(c);
cout << endl;
}
Here, the
'\n'
left by cin, is creating issues.This
\n
is being consumed by next getline increateNewCustomer()
. You should use getline instead -I think this would resolve the issue.
If you're using
getline
aftercin >> something
, you need to flush the newline out of the buffer in between.My personal favourite for this if no characters past the newline are needed is
cin.sync()
. However, it is implementation defined, so it might not work the same way as it does for me. For something solid, usecin.ignore()
. Or make use ofstd::ws
to remove leading whitespace if desirable:I faced this issue, and resolved this issue using getchar() to catch the ('\n') new char
The structure of your menu code is the issue: