Exceeding scanf's maximum input (Standard C)

  • Thread starter Thread starter spursfan2110
  • Start date Start date
  • Tags Tags
    Input Maximum
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 3K views
spursfan2110
Messages
19
Reaction score
0
Hey everyone, I have a kind of large problem.

I am trying to input something in C, a number between 0 and 50,000, using scanf(). I understand how scanf generally works, and it does for the most part, but for some reason if the number I enter is greater than 37504, the program just stops. Doesn't freeze, doesn't crash, just stops. I have tried changing the data type from int, and have tried unsigned int and long int as well, any other suggestions about what's going on? Thanks!

Here's the pertinent part of code:

int main ()

{long int &max;


printf("Enter an integer between 2 and 50,000: ");
scanf("%ld", &max);

etc.
 
Last edited:
Physics news on Phys.org
The declaration should be "long int max" (that is, remove the '&').

(Does it even compile as is?)
 
It is always instructive to tell the compiler to give you all warnings.
"long int &max;" is not standard C. Self respecting C compilers won't even compile your code.
It is bad practice to use C++. C++ is a language which successfully combined all bad properties of a low-level programming language and an object-oriented one. If you want to stay close to hardware or write fast code use C, if you want to code clean and fast, use python or ruby.
Here is your code edited a bit:
Code:
#include <stdio.h>
int main ()
{
long int &max;
printf("Enter an integer between 2 and 50,000: ");
scanf("%ld", &max);
}
This is what GNU c says to it:
Code:
p$ gcc -Wall a.c -c
a.c: In function ‘main’:
a.c:4: error: expected identifier or ‘(’ before ‘&’ token
a.c:8: error: ‘max’ undeclared (first use in this function)
a.c:8: error: (Each undeclared identifier is reported only once
a.c:8: error: for each function it appears in.)
this is what GNU c++ says:
Code:
$ g++ -Wall a.c -c
a.c: In function ‘int main()’:
a.c:5: error: ‘max’ declared as reference but not initialized
So max is declared as a reference. it is something like a pointer, but in the confused c++ way.
First and foremost, you should tell in declaration time what it refers to.
But I suggest to forget this c++ crap, and use a normal long int variable instead, and everyone will be happy.
And read something about pointers: http://home.netcom.com/~tjensen/ptr/pointers.htm