C++ program to check given string is numeric or not

Learn: How to check given string is numeric or not? In this C++ program, we are going to learn how to check whether a given a string is numeric or not?
[Last updated : February 26, 2023]

Checking the given string is numeric or not

This program will take a string and check whether string is numeric or not in C++ language, this is common sometimes while writing such a code where we need to validate a string with numeric. This program is useful for such kind of requirement.

C++ code to check whether a given string is numeric or not

#include <iostream>
using namespace std;

int isNumericString(unsigned char* num)
{
    int i = 0;
    while (*(num + i)) {
        if (*(num + i) >= '0' && *(num + i) <= '9')
            i++;
        else
            return 0;
    }
    return 1;
}

int main()
{
    int ret = 0;
    unsigned char str1[] = "123";
    unsigned char str2[] = "ABC";

    ret = isNumericString(str1);
    if (ret)
        cout << "It is numeric string" << endl;
    else
        cout << "It is not numeric string" << endl;

    ret = isNumericString(str2);
    if (ret)
        cout << "It is numeric string" << endl;
    else
        cout << "It is not numeric string" << endl;

    return 0;
}

Output

It is numeric string
It is not numeric string

See the program; here str1 contains numeric string while str2 does not contain numeric string. Program is validating the string as numeric or not.



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.