Check if string is number in C++
In this tutorial, we will learn how to check whether the string is a number using C++. To better understand the problem, we are going to see some examples.
For Example: Let us take three input strings string s1 = "CodeSpeedy" string s2 = "c++" string s3 = "54655449" So Now the Output will be Not Number Not Number Number Now to solve this problem we are going to use the std::isdigit() function method. It is the fastest method to implement the solution.
Approach to the Problem
We just have to pass a string as a parameter that iterates and checks the string in each character-wise. As it finds out the first non-number character in the string, It returns False, and if not it returns True.
C++ program to check if a string is number or not
// Program to find the string is a number #include <iostream> #include <algorithm> using namespace std; // Function to check the string character by character bool isNumber(string& str) { for (char const &c : str) { // using the std::isdigit() function if (std::isdigit(c) == 0) return false; } return true; } //Driver Code int main(){ string str1 = "2Codespeedy"; string str2 = "2222313232"; string str3 = "a31C++"; isNumber(str1) ? cout << "Number\n" : cout << "Not number\n"; isNumber(str2) ? cout << "Number\n" : cout << "Not number\n"; isNumber(str3) ? cout << "Number\n" : cout << "Not number\n"; return 0; }
OUTPUT Not Number Number Not Number
We can also use std::stoi()
function and it will work on negative numbers too:
#include <iostream> #include <string> bool is_number(const std::string& s) { try { std::stoi(s); } catch (std::exception& e) { return false; } return true; } int main() { std::string s = "12345"; if (is_number(s)) { std::cout << s << " is a number." << std::endl; } else { std::cout << s << " is not a number." << std::endl; } return 0; }
Also read: How to check the current C++ version using Program
It won’t work for negative integers (“-69”) or if you specify positive integers with ‘+’ sign like “+69”.
We have added a code that will work for negative numbers also. Thanks for your suggestion.
You forget about empty condition.
Empty string gives positive result in your case so it means it is number.