This code looks simple, right?
string password;
cin.ignore();
getline(cin, password);
cout << "The user inputted the password: " << password << endl;
Well for some reason when i type in "secret" as the password the cout results in only "ecret" , ie it is chopping off the first character every time. Why is this?
cin.ignore()
ignores the next character of input. That means the s
in secret
. I imagine the call is there because of previous troubles of getline
seeming to skip input (see this question ). This only applies when operator>>
is used and leaves a newline beforehand. I recommend instead doing:
getline(std::cin >> std::ws, password);
This will remove troubles over leftover whitespace and not cause problems when there is none.
You can just do this..
string password;
cout << "enter password:";
getline(cin, password);
cout << "The user inputted the password: " << password << endl;
Alternatvely , you can use cin to receive inputs. Now you can use cin.ignore.
string password;
cout << "enter password:";
cin >> password;
cin.clear();
cin.ignore(200, '\n');
cout << "The user inputted the password: " << password << endl;
It is good to use cin.clear()
and cin.ignore()
when you are receiving inputs using cin >>
. However, if you are using getline()
, it seems unnecessary to use cin.ignore()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.