Error Handling

I need to do some error handling in c++ that not only corrects a user if they enter a negative number, but also if they enter a letter or string. I need to use .at(), .length(), and atoi to handle this. I'm not sure how/where to implement those is the problem. What I have so far asks the user 5 times to guess the number, however as mentioned before, I'm unsure of where to put .at(), .length, and atoi so that everything doesn't crash and burn when I do. Thanks for the help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>

using namespace std;

int main() {
    
    
    srand(time(0));
    int number;
    number = rand() % 50 + 1;
    int guess;
    int x;
    
    
    for (x = 5; x > 0; x--) {
        cout << "Guess my number, it's between 0-50. You have 5 guesses: ";
        cin >> guess;
        if (guess < number){
            cout << "Your guess was too low" << endl;
        }
        else if (guess > number){
            cout << "You guess was too high" << endl;
        }
        else {
            cout << "You're exactly right!" << endl;
            break;
        }
    } while (guess != number){
        break;
    }
    
    
    
    
    return 0;
}
.
Last edited on
Fetch the input as a string.
Look at each char in the string.
If any char is NOT in the set 0-9 , reject and start again.
Convert string to int using http://en.cppreference.com/w/cpp/string/basic_string/stol
First off, if you want to test for a user entering a string or a letter, you'll need to cin a string, test it for numeric, then convert it.
1
2
3
4
5
6
7
8
9
10
11
12
13
int get_number () 
{   string  str;
    
    while (true)
    {   cin >> str;
        for (unsigned i=0; i<str.length(); i++)
            if (! isdigit(str.at(i)))
            {   cout << "Number is not numeric" << endl;
                continue;
            }
        return stoi(str)
  }
}


edit:
Line 19 is incorrect. At line 13 you generating a number between 1 and 50.
Last edited on
1
2
3
while (guess != number){
   break;
}
O_o


For the conversion, atoi() would be no good as 0 is a valid input.
Use this instead http://www.cplusplus.com/forum/articles/9645/#msg44710
Topic archived. No new replies allowed.