c++ - String getline(cin,variable) function is skipping some lines of code -
my programme skips code when utilize getline(cin,variablehere) function. don't know whats wrong code. see output below
#include <iostream> #include <string> using namespace std; int main() { string getfirstname; string lastname; string address; int contactnumber; cout << "enter first name : "; getline(cin, getfirstname); cin.ignore(); cout << "enter lastly name : "; getline(cin, lastname); cin.ignore(); cout << "enter address : "; getline(cin, address); cin.ignore(); cout << "enter contact number : "; cin >> contactnumber; cin.ignore(); currentnumberofcontacts += 1; cout << "successfully added contact list!" << endl << endl; cout << "would add together contact ? [y/n] "; cin >> response; //more lines of codes below homecoming 0; } i have inputed 'int' info type because contain numbers only
i recommend removing all cin.ignore() commands.
one of problems user input >> operator not take homecoming character out of stream if follow getline() getline() read homecoming character instead of want type in.
so alter all getline() this:
// cin >> ws skip homecoming characters // may left in stream getline(cin >> ws, lastname); also remove all of cin.ignore() commands. not doing useful when used after getline() command , if alter getline() commands showed should not necessary @ all.
so should work:
int main() { string getfirstname; string lastname; string address; char response; int contactnumber; int currentnumberofcontacts = 0; cout << "enter first name : "; getline(cin >> ws, getfirstname); cout << "enter lastly name : "; getline(cin >> ws, lastname); cout << "enter address : "; getline(cin >> ws, address); cout << "enter contact number : "; cin >> contactnumber; currentnumberofcontacts += 1; cout << "successfully added contact list!" << endl << endl; cout << "would add together contact ? [y/n] "; cin >> response; //more lines of codes below homecoming 0; } strictly speaking not of getline() functions need employ cin >> ws trick. suppose (incomplete) rules follows:
if utilize std::getline() after >> use:
std::getline(cin >> ws, line); otherwise use:
std::getline(cin, line); c++
No comments:
Post a Comment