Checking Valid Numbers in C++

Samuel Adesola
2 min readSep 30, 2022

Overview

In this task, we will be going over numbers validation. In some scenarios, we might want to check if the user input is a valid number or not or sometimes we might want to parse some set of data, in these cases, writing a program that automatically checks if a number is valid or not is important. The following were given in the task as what makes a number valid:

A valid number can be split up into these components (in order):

  1. A decimal number or an integer.
  2. (Optional) An 'e' or 'E', followed by an integer.

A decimal number can be split up into these components (in order):

  1. (Optional) A sign character (either '+' or '-').
  2. One of the following formats:
  3. One or more digits, followed by a dot '.'.
  4. One or more digits, followed by a dot '.', followed by one or more digits.
  5. A dot '.', followed by one or more digits.

An integer can be split up into these components (in order):

  1. (Optional) A sign character (either '+' or '-').
  2. One or more digits.

Thought Process

There are different methods this can be achieved. One of the most convenient ways is to iterate over the set of the input and compare each element with the conditions stated above, the function can then return true or false if the conditions are met or not.

Following this approach, the code can be written traditionally using conditionals i.e if and else but to implement this I use the concept of regex in C++.

static regex num(R”_([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)_”);

With regex, all these conditions can be fused into a single line of code thereby achieving more compile-time and runtime speed.

Conclusion

Writing code that can be used as an automation tool can be quite important and this is one. With numbers validation code, various processes can be sped up in software development.

Also, this will be the last day in this 10 days streak and I will say a big thanks to the motivation behind all these wonderful writeups, Ingressive for good.

--

--

Samuel Adesola

I am an embedded system engineer. Most of my works focus on IoT, AI and Machine Learning. With years of experience in programming and electronics