Logic Error: Validating a string input.

Hey guys, I've been working on some code that is supposed take in a string, test if the string contains integers only, and then convert it to a double.

It is working mostly as intended, except for this one specific case: It will reject a string like "abcde123" and ask for another input. However, when you enter "123abcde" it does not ask for another input, it simply accepts the integers, ignores the characters, and continues without error.

I would be very appreciative if someone could help me narrow down the error in my logic. I'm thinking it has something to do with how 'atof()' works, or there's something off with my 'is_number' function.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 while (true) {
    cout << "Enter a roster number for " << player[i].name << ": ";
    getline (cin, userInput);

    if (is_number(userInput) && atof(userInput.c_str()) > 0 ) {
      player[i].rosterNum = atof (userInput.c_str());
      break;
    }
    else
      cout << "That is not a valid roster number; Try a positive integer." << endl;
}

bool is_number (const string& input) {
    for (int i = 0; i < input.length(); i++) {
       char in_char = input[i];
       if (!isdigit(in_char)) {
          return false;
          break;
       }
       else
          return true;
    }
}
Topic archived. No new replies allowed.