The code looks basically OK.
Assuming that
GetLongLong()
returns a
long long
, the error may occur when the input is larger than
LONG_MAX
(2147483647) when converted to
long
. However, there should be a compiler warning on that line because no casting is used.
If so, this can be solved by using
long long
for NUM too.
Side note: Don't use all upper case variable names with C/C++. These are usually used only with
#define
s.
The error may also occur in the
GetLongLong()
function for which you did not show the code.
[EDIT]
Answering the comment
Quote:
I tried adding long long for NUM, but that didn't help. GetLongLong() is supposed to be a built-in function.
GetLongLong()
is not a standard library function. I found this (
[
^]):
long long
GetLongLong(void)
{
while (true)
{
string line = GetString();
if (line == NULL)
return LLONG_MAX;
long long n; char c;
if (sscanf(line, " %lld %c", &n, &c) == 1)
{
free(line);
return n;
}
else
{
free(line);
printf("Retry: ");
}
}
}
It explains why "Retry" is printed in the output. All I can assume now is that the
sscanf
implementation of the used library is failing to scan 64-bit integers.
However, the input "123456789" should work because it is less than
LONG_MAX
.
You may try to use
strtoll - C++ Reference[
^] instead:
long long GetLongLong()
{
char *endptr;
string line = GetString();
long long num = strtoll(line, &endptr, 10);
free(line);
return num;
}
[/EDIT]