Check if a given string is a valid number in C++

Concept

It should be validated if a given string is numeric.

Input − str = "12.5"

Output − true

Input − str = "def"

Output − false

Input − str = "2e5"

Output − true

Input − 10e4.4

Output − false

Method

We have to handle the following cases in the code.

  • We have to ignore the leading and trailing white spaces.

  • We have to ignore the ‘+’, ‘-‘ and’.’ at the start.

  • We have to ensure that the characters in the string belong to {+, -, ., e, [0-9]}

  • We have to ensure that no ‘.’ comes after ‘e’.

  • A digit should follow a dot character ‘.’.

  • We have to ensure that the character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit.

Example

 Live Demo

// C++ program to check if input number
// is a valid number
#include 
#include 
using namespace std;
int valid_number1(string str1){
   int i = 0, j = str1.length() - 1;
   while (i = 0 && str1[j] == ' ')
      j--;
   if (i > j)
      return 0;
   if (i == j && !(str1[i] >= '0' && str1[i] = '0' && str1[i] = '0' && str1[i]  str1.length())
            return 0;
         if (!(str1[i + 1] >= '0' && str1[i + 1] = '0' && str1[i - 1]  str1.length())
            return 0;
         if (str1[i + 1] != '+' && str1[i + 1] != '-'
            && (str1[i + 1] >= '0' && str1[i] 

Output

true
Updated on: 2020-07-23T07:51:03+05:30

585 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements