I need a way to convert a variable to an int or to ascii code, tried atoi, static_cast, didnt work very well... The objective is to detect if the user inserted any character other than a number, a number smaller than 0 or larger than 5, and send a message if so...
Here is the program with one of my tries...

#include<cstdlib>
#include<cstdio>
#include<iostream>

using namespace std;

int main()
{
    while(1)
    {
         back:
         cout << "Insert two numbers" << endl;
         int num1, num2;
         cin >> num1 >> num2;
         int a = static_cast<int> (num1);
         int b = static_cast<int> (num2);
         if ( ( a <= -1 ) || ( a > 5 ) || ( b <= -1 ) || ( b > 5) )
         {
                cout << "Incorrect input" << endl;
                goto back;
         }
         if ( fim(tabuleiro) )  break; //please dont mind this, this is a small part of a bigger program
    }
}

Please note that im quite new at programing so if anyone has any tips i would apreciate it =)
Thank You.

Why do you need to cast or even make a and b? Just test num1 and num2:

using namespace std; 
int main()
{
    while(1)
    {
         int num1, num2;
         cout << "Insert two numbers" << endl;
         cin >> num1 >> num2;
         if ( ( num1 <= -1 ) || ( num1 > 5 ) || ( num2 <= -1 ) || ( num2 > 5) )
         {
                cout << "Incorrect input" << endl;
         }
    }
}

Hum, what if the user inserts a character or something else? Shouldnt be able to compare with an int should it?

...
num1 is already of int type, you WOULDN'T be able to enter a character anyway.

commented: a char is an 8-bit integer. get your basic facts straight before "helping" please +0

...
num1 is already of int type, you WOULDN'T be able to enter a character anyway.

Why not? Just press something on the keyboard.

It would be a good idea to check wether the input is int or not.
Perhaps something like:

using namespace std; 
int main()
{
    while(1)
    {
         int num1, num2;
         cout << "Insert two numbers" << endl;
         cin >> num1 >> num2;
         cin.ignore(numeric_limits<int>::max(), '\n');
         if (!cin || cin.gcount() != 1)
            cout << "Not a number\n";

         else if ( ( num1 <= -1 ) || ( num1 > 5 ) || ( num2 <= -1 ) || ( num2 > 5) )
               cout << "Incorrect input" << endl;
    }
}

That should take care of invalid input. Didn't test it though

[edit] and don't forget to #include <limits>

Worked out great, thanks a lot ;)
Really helpful =D
Exactly what i wanted...

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.