Home » C++ programs » C++ Most popular & searched programs

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?

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.

Consider the program:



#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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.