You might consider this question a follow-up of:
BigInteger check in C from a string
Although, this time, I used C++.
I am on Linux Mint 19.1 with the compiler version:
g++-8 (Ubuntu 8.2.0-1ubuntu2~18.04) 8.2.0
I tried to push myself hard in C, but it obviously requires one of:
more skill / experience
lower-level approach
or both.
That is why I decided to transition to C++, already bought one C++ online course on Udemy, but back to coding, the current version looks straightforward to me, I see no more pointers, etc., which sounds ideal to me:
#include <iostream>
//#include <string> // I don't get why it compiles without this header
bool string_contains_integer(std::string str)
/*
This function iterates through an array of chars,
and checks each character to be a digit;
optionally including a starting "+/-" sign.
Returns true if the string contains a number (string of digits);
Returns false if the string contains another character(s).
Starting "+/-" gets ignored, as we accept all integer numbers.
*/
{
// if the string is empty, return right away
if ( str.empty() ) return false;
// I'd like to avoid repeated length() calls
unsigned long long string_length = str.length();
// find out if there is a "+/-" sign
bool sign_present = ( (str[0] == '-') || (str[0] == '+') );
// check if there is the sign only
if ( sign_present && (string_length == 1) ) return false;
// iterate through all characters in the string
for (unsigned long long i = 0; i < string_length; i++)
{
// skip the digit check for the sign at the beginning
if ( (i == 0) && sign_present ) continue;
// this is actually the core part checking on digits
if ( ! std::isdigit( (unsigned char) str[i] ) ) return false;
}
// If we got here, then all the characters are digits,
// possibly starting with a sign.
return true;
}
int main(void)
{
if ( string_contains_integer("-123456789123456789123456789123456789123456789123456789123456789") )
{
std::cout << "PASS: Input is a number.\n";
return 0;
}
else
{
std::cerr << "FAIL: Input is not a number!\n";
return 1;
}
}
This program I compile as follows:
g++-8 -std=c++17 -Wall -Wextra -Werror -Wpedantic -pedantic-errors -o bigInteger bigInteger.cpp