cin and getline skipping input

c++, cin, getline, input

Solution

If you're using `getline` after `cin >> 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, use `cin.ignore()`. Or make use of `std::ws` to remove leading whitespace if desirable:

int a;

cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 
//discard characters until newline is found

//my method: cin.sync(); //discard unread characters

string s;
getline (cin, s); //newline is gone, so this executes

//other method: getline(cin >> ws, s); //remove all leading whitespace

Problem

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; } ```

Original source

Related problems