6 Years
Discussion Span
Last Post by Narue

are you asking about how to identify whether user entered a integer or other?

well one way of doing that is fetching the input stream (std::cin) to (std::string) and then parse it for correct format.For that you can write your own state machine or
you can use regex for this.

If you need any help while creating the state machine just ask,I'll see what I
can do for you.


Human tend to be creative and bend the rules. There is no way to be sure that the input you received is in integer format. The best way is to read line and then try to parse the string into integer.


#include <stdlib.h>

int i;
char num[256];

i = atoi(num);

>There is no way to be sure that the input you received is in integer format.
No standard way, at least if you want to force integer input at the keystroke level. If you can get raw input, you can force the user to enter whatever you want. In this case, the digits can be parsed on the fly as they're typed:

#include <cctype>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <conio.h>

int get_int()
    const int base = 10;

    int c = getch();
    int result = 0;
    bool sign = 0;

    if (c == '-' || c == '+') {
        sign = c == '-';
        c = getch();

    int limit = std::abs((sign ? INT_MIN : INT_MAX) / base);
    int top_digit = std::abs((sign ? INT_MIN : INT_MAX) % base);

    while (std::isdigit(c)) {
        int digit = c - '0';

        if (result > limit || (result == limit && digit > top_digit))

        result = result * base + digit;
        c = getch();

    return sign ? -result : result;

#include <iostream>

int main()
    std::cout<<"\nValue read: "<< get_int() <<'\n';

But that's tedious and non-portable. It's much easier to read a string, parse it, and prompt for valid input if the input doesn't meet the program's needs.

Edited by Narue: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.