Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
// C++ program to check if input number
// is a valid number
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int valid_number1(string str1){
int i = 0, j = str1.length() - 1;
while (i < str1.length() && str1[i] == ' ')
i++;
while (j >= 0 && str1[j] == ' ')
j--;
if (i > j)
return 0;
if (i == j && !(str1[i] >= '0' && str1[i] <= '9'))
return 0;
if (str1[i] != '.' && str1[i] != '+' && str1[i] != '-' && !(str1[i] >= '0' && str1[i] <= '9'))
return 0;
bool flagDotOrE = false;
for (i; i <= j; i++) {
// If any of the char does not belong to
// {digit, +, -, ., e}
if (str1[i] != 'e' && str1[i] != '.'
&& str1[i] != '+' && str1[i] != '-'
&& !(str1[i] >= '0' && str1[i] <= '9'))
return 0;
if (str1[i] == '.') {
if (flagDotOrE == true)
return 0;
if (i + 1 > str1.length())
return 0;
if (!(str1[i + 1] >= '0' && str1[i + 1] <= '9'))
return 0;
}
else if (str1[i] == 'e') {
flagDotOrE = true;
if (!(str1[i - 1] >= '0' && str1[i - 1] <= '9'))
return 0;
if (i + 1 > str1.length())
return 0;
if (str1[i + 1] != '+' && str1[i + 1] != '-'
&& (str1[i + 1] >= '0' && str1[i] <= '9'))
return 0;
}
}
return 1;
}
// Driver code
int main(){
char str1[] = "0.1e10";
if (valid_number1(str1))
cout << "true";
else
cout << "false";
return 0;
}
Output
true
Advertisements