atoi trouble

For my programming class I'm trying to create a number guessing game and I need to use atoi() so that if the user enters a character string, it yields an error saying it needs to be an integer. I have no clue how to do this.

Here's my code. Everything is working except for my atoi part.

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
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){

int max_num;
int num_guess, guess;
int hidden;
int num_tries;
int seed;
int i;



    cout << "Enter the maximum possible hidden number: ";
    cin >> max_num;
    cout << "Enter the number of guesses to allow: ";
    cin >> num_guess;
    
    seed = time(0);
    srand(seed);
    hidden = (rand()%max_num) + 1;
    
    
    for(num_tries=1; num_tries<=num_guess; num_tries++){
        cout << "Guess <1 -" << max_num << ">: ";
        cin >> guess;
        if(guess > hidden){
            cout << "The guess was too high." << endl;
        }
        else if(guess < hidden){
            cout << "The guess was too low." << endl;
        }
        else if(guess = hidden){
            cout << "Correct!" << endl;
            cout << "It took you " << num_tries << " tries." << endl;
            system("pause");
            return 0;
        }
           
    }
    if(num_tries > num_guess){
        cout << "The number of tries has run out." << endl;
        cout << "The hidden number was " << hidden << endl;
    }  
    
    system("pause");
    
    }
atoi() has no means by which to report an error to the caller reliably. You need to use strtol or strtoul instead.
Topic archived. No new replies allowed.