This post will discuss how to determine if a string begins with a number in C++.

1. Using isdigit() function

A simple solution is to extract the first character from the string, and check if it is numeric or not. This can be easily done using the isdigit() function, as demonstrated below:

Download  Run Code

 
Note the length check before accessing the first character from the string. The above code is roughly equivalent to:

Download  Run Code

2. Using Regex

Another option is to use a regular expression to determine whether a string begins with a number. Since C++11, we can use std::regex_match to match a sequence against a regex object. For example,

Download  Run Code

That’s all about determining if a string begins with a number in C++.