Get a number

Hi everyone,
This is not how I get numbers from the user, but I wanted to try a new method.
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
#include <iostream>
#include <cstdlib>
using namespace std;

void get(int& a);

int main()
{
    int n;
    cout<<"Enter a number:  ";
    get(n);
    cout<<n<<endl<<endl;
    cin.get();
    return 0;
}

void get(int& a)
{
    char temp[65];

    while(true)
    {
        cin.getline(temp, 65);

        if(atoi(temp))
        {
            a=atoi(temp);
            return;
        }
        else
        {
            cout<<"\aInvalid:  ";
        }
    }
}

It works pretty well, but if you hold down, say the "a" key, for a few lines(more than 80 characters) it crashes. It continuously prints "Invalid:". I don't know if the array is overflowing or if it's the integer (or if there's another problem). Do not run this and try to crash it unless you are running it in debug mode. Thanks for your help.
Last edited on
It breaks if you have invalid input longer than 65 characters long because you don't break out of the while loop if the input is invalid.
1
2
3
4
        else
        {
            cout<<"\aInvalid:  ";
        }

Should be:
1
2
3
4
5
        else
        {
            cout<<"\aInvalid:  ";
            return; // or break;
        }


Also, if you enter '0', atoi returns 0, triggering the else statement.
Topic archived. No new replies allowed.