How to check if a C/C++ string is an int?

C++ProgrammingServer Side Programming

There are several methods to check that string is an int or not and one of those method is to use isdigit() to check the string.

Here is an example to check whether a string is an int or not in C++ language,

Example

 Live Demo

#include<iostream>
#include<string.h>

using namespace std;
int main() {
   char str[] = "3257fg";

   for (int i = 0; i < strlen(str); i++) {
      if(isdigit(str[i]))
      cout<<"The string contains int\n";
      else
      cout<<"The string does not contain int\n";
   }
   return 0;
}

Output

Here is the output

The string contains int
The string contains int
The string contains int
The string contains int
The string does not contain int
The string does not contain int

In the above program, the actual code of checking the string is present in main() function. Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.

for (int i = 0; i < strlen(str); i++) {
   if(isdigit(str[i]))
   printf("The string contains int\n");
   else
   printf("The string does not contain int\n");
}
raja
Published on 24-Oct-2018 10:31:53
Advertisements