0

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?

SOLVED

(See comments below)

Axel Kennedal
  • 443
  • 5
  • 16

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
  • 55,166
  • 13
  • 130
  • 185
  • 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
  • 16,235
  • 13
  • 52
  • 96