DomeWTF
DomeWTF

Reputation: 2420

how to check if the user input an integer

I need to check in my program if the user inputs an integer and not a character or string. Character isn't that bad since it's pratically an integer, but if the user enters a sequence of characters then it just goes nuts.

I've made this function

int* ask_lung(int* lung)
{
int tmp; // length of a word

cout << "Inserisci la lunghezza della parola da indovinare: ";
cin >> tmp;

if(cin)
{
    // Se i è uguale a o minore di 0 allora ritorna all'inizio

    if(tmp <= 0)
    {
        cout << endl << "\tNon puoi inserire 0." << endl << endl;
        ask_lung(lung);
    }
    else
    {
                    // the error is about here, when it reaches this part of the code it keeps showing the first line "Inserisci la lunghezza della parola da indovinare: "
        *lung = tmp;
    }
}
else ask_lung(lung);

return lung;
}

Upvotes: 1

Views: 6936

Answers (3)

Coding Mash
Coding Mash

Reputation: 3346

In case of string of characters, your stream contains large number of invalid characters and you need to flush your stream of those characters to a new state. Instead of doing that recursively, it is better to do that in a loop. This would suffice for you reasonably.

while(true)
{
  cout << "Please Enter an Integer" << endl ;
  if (cin >> temp)  //true if a leading integer has entered the stream
    break ;
  else
  {
    cout << "Invalid Input" << endl ;
    cin.clear() ;
    cin.ignore(std::numeric_limits<streamsize> :: max(), '\n') ;
  }
}

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361332

You can use std::all_of along with std::isdigit as:

std::string input;
std::cin >> input;

if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
     //input is integer
}

Or, if you want to test and also want the integer, then it is better to use input as int, as suggested by other answer. You may consider using std::stoi if you have (read) the string already. Note that std::stoi throws exception on error.

Upvotes: 1

user1610015
user1610015

Reputation: 6668

The input is handled correctly, the problem is that you're returning a pointer to a local variable. That variable is on the stack, an it will be deallocated once the function returns. Instead you should just return the integer itself, not a pointer to it.

EDIT: I see that actually you're not returning a pointer to the integer, you're assigning to the integer that the pointer points to. Still, it's better to just return the integer itself.

Upvotes: -2

Related Questions