-1

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", i.e. it is chopping off the first character every time. Why is this?

Vega
  • 27,856
  • 27
  • 95
  • 103
Axel Kennedal
  • 527
  • 6
  • 22

2 Answers2

1

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.

Community
  • 1
  • 1
chris
  • 60,560
  • 13
  • 143
  • 205
  • What is that "std:ws"? I get the rest though, thanks! – Axel Kennedal Apr 10 '14 at 16:53
  • @AxelKennedal-TechTutor, It extracts leading whitespace. – chris Apr 10 '14 at 16:57
  • Extracts? Could you explain from the top to the bottom how that line works? :) – Axel Kennedal Apr 10 '14 at 19:16
  • @AxelKennedal-TechTutor, `std::cin >> std::ws` reads the whitespace at the beginning and throws it away. For example, if you have an input buffer of `\n \t Axel Kennedal\n`, the spaces, tab, and newline would be removed and the input buffer would be left with `Axel Kennedal\n`. The returned value of this is `std::cin`, which is what you pass in anyway, but now the buffer is short of the whitespace. Then, `std::getline` goes and reads until the newline like normal, but now it doesn't get any of that whitespace that existed at the beginning of the input. – chris Apr 10 '14 at 22:05
0

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().

user3437460
  • 17,253
  • 15
  • 58
  • 106