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.

Dani AI

Generated

A reliable pattern for this kind of validation is to read a full input line and then parse it. That way the program can detect non-numeric characters, missing or extra tokens, and still perform range checks (0..5). Reading with std::getline into a std::string and then using std::istringstream keeps cin clean and makes it straightforward to reject malformed input.

#include <iostream>
#include <string>
#include <sstream>

bool readTwoIntsInRange(int &a, int &b, int minv, int maxv)
{
    std::string line;
    if(!std::getline(std::cin, line)) // EOF or error
        return false;

    std::istringstream iss(line);
    if(!(iss >> a >> b))               // not two integers
        return false;

    char extra;
    if(iss >> extra)                   // extra non-space input found
        return false;

    return (a >= minv && a <= maxv && b >= minv && b <= maxv);
}

int main()
{
    int x, y;
    while(!readTwoIntsInRange(x, y, 0, 5))
        std::cout << "Incorrect input\n";
    // validated x and y here
}

This addresses the issues raised in the thread: is right that casting the already-int values is unnecessary; is mistaken to imply characters cannot be typed (typing letters will cause parsing to fail); and 's idea of checking the stream state is on the right track, but the getline+istringstream approach tends to be simpler and less error-prone. Extra notes: handle EOF if needed, and adapt the check if single-digit-only input (0..5) is required (e.g., reject multi-digit numbers like 12).

Recommended Answers

All 5 Replies

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.