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
Also read: How to check the current C++ version using Program
Leave a Reply