0

I have some code: I wish to take in an ID, make sure it's of 8 chars in length, make sure each digit is a number, and continue to ask until they give the correct input. BEFORE SOMEONE MARKS THIS DOWN, i researched and tried to look at answers given :c I don't get why it says the id I enter 00000002 is an Invalid ID according to my code. It's not working. can anyone help?

void Student::getData(){
    string id_;

    cout << "lastName?" << endl;
    cin >> lastName;

    cout << "firstName?" << endl;
    cin >> firstName;

    cout << "ID?" << endl;
    while(getline(cin,id_) && id_.size() != 8){
    cout << "Invalid ID" << endl;
    }
  • 2
    Have you added a cout to see what the actual size of `id_` is? that would help you debug a bit more. – scrappedcola Sep 25 '15 at 18:27
  • Recommend investing some time in learning to use the debugger that comes with your IDE. It would have shown you what was happening almost instantly. It wouldn't have told you why, but would have made your search for an answer much easier. This is a question that's asked a couple times a week. We might need a "why does getline fail?" pseudo question for which it is easier to search. – user4581301 Sep 25 '15 at 18:44

1 Answers1

2
while(getline(cin,id_) && id_.size() != 8){

Here getline() just gets the newline left over from the previous line of input. Add a line to ignore the rest of the line before that.

cin.ingore(std::numeric_limits<std::streamsize>::max(), '\n');
while(getline(cin,id_) && id_.size() != 8){
R Sahu
  • 204,454
  • 14
  • 159
  • 270