1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Exceeding scanf's maximum input (Standard C)

  1. Feb 24, 2010 #1
    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: Feb 24, 2010
  2. jcsd
  3. Feb 25, 2010 #2
    The declaration should be "long int max" (that is, remove the '&').

    (Does it even compile as is?)
     
  4. Feb 25, 2010 #3
    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 (Text):

    #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 (Text):

    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 (Text):

    $ 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
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook