I am studying C++ and after I learned about some functions of the library cctype
like isdigit
I decided to make a program that validates user input only to be an integer number. So input like 123as
, :$
or +.234
are invalid, however I decided to keep the plus or minus sign, i.e., input like -24
or +142
are valid. Below is my code:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool integer_valid(string s);
int get_integer();
int main()
{
int number;
number = get_integer();
cout << "The integer number is:\t" << number << "\n" << endl;
system("pause");
return 0;
}
bool integer_valid(string s)
{
int i, length_s;
bool is_valid = true;
length_s = s.length();
if (length_s == 0)
is_valid = false;
else
{
if (length_s == 1)
{
if (!isdigit(s[0]))
is_valid = false;
}
else
{
if (s[0] == '+' || s[0] == '-' || isdigit(s[0]) != 0)
{
for (i = 1; i < length_s; i++)
{
if (!isdigit(s[i]))
is_valid = false;
}
}
else
is_valid = false;
}
}
return is_valid;
}
int get_integer()
{
int new_number;
string number;
bool is_valid;
do {
cout << "Enter an integer number:\t";
getline(cin, number);
cout << "\n";
is_valid = integer_valid(number);
if (is_valid == false)
cout << "ERROR. The entered number must be an integer.\n" << endl;
} while (is_valid == false);
new_number = stoi(number);
return new_number;
}
I'm aware that in general is a bad practice to use using namespace std
, but since my program has less tan 100 lines of code I think it's really not a big issue here. Moreover, I wonder if there is another (simpler/faster) way to validate integer numbers?
EDIT: Answering to the comment made by Roland Illig, I would say yes. More exactly, any kind of integer should be valid, but as far as I know, int
has a defined size, so if I want to valid long integers I should use the type long long int
and also the function stoll
, right?
Any feedback would be greatly appreciated.
111111111111111111111111111111111
a valid integer to you? \$\endgroup\$