I want it to do the following:
Ask for a number between 1 and 5, if user inputs anything lower, higher, or something that isn't a number, it should give an error message and then ask for a input again.

This code will spam the error message forever,
what have I done wrong?

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <cmath>
using namespace std;


int main()
{
    //vars
   int user_number;
  
  
   cout
   <<"Please pick a number between 1 and 5"
   <<endl
   <<endl;
   
   cin >> user_number;
   while(user_number<1 || user_number >5 || isdigit(user_number)==false)
   {
   cout <<"I said a number between 1 and 5! =(" <<endl;
   cin >> user_number;                   
   }
   cout <<"You choose "<<user_number;
    
    
 
 system("pause");
 return 1;
}

Since your numbers are single digits, take in your input as a character and check to see if it's a digit (the isdigit is meant for characters). See if you can rewrite the condition of your while loop to account for numbers in the right range (hint, look at an ASCII table).

hello...try this
1. suppose i input a character. the compiler cannot store character as integer. ERROR

i stored in char a variable input and converted it into integer using atoi(). it returns 0 for all character values. hence no need to use isdigit().

#include <iostream>
#include <stdlib.h>
using namespace std ;
 void main()
 {
	char input[2] ;
	int user_number ;
	cout <<"Please pick a number between 1 and 5" <<endl <<endl ;

   cin >> input ;
   while( user_number = atoi ( input ) , user_number<1 || user_number >5 )
   {
   cout <<"I said a number between 1 and 5! =(" <<endl ;
   cin >> input ;
   }
   cout <<"You choose "<< user_number ;
   system ("pause") ;
 }

i left u a bug here. it converts values like 3.75 to integer(3) and program runs. try and solve and avoid isdigit(). just stick to easy statements... i feel they are quite reliable..

i left u a bug here.

Rather than do that, guide the poster to the right answer without any of this bug squashing.

try and solve and avoid isdigit()

And your reason is? In reality, you can do it without either by using the characters in the comparison (e.g., c < '1'), but I don't want to steal all the fun.

Rather than do that, guide the poster to the right answer without any of this bug squashing.


And your reason is? In reality, you can do it without either by using the characters in the comparison (e.g., c < '1'), but I don't want to steal all the fun.

Thank you for guidance..that was my first post. ill work on that and be better next time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.