Thread: scanf trouble: easy code, inexperienced programer

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    9

    scanf trouble: easy code, inexperienced programer

    When ever I use scanf("%d", &n) ; and then have a following printf("Generic Statement:"); My compiler displays the printf statement without me inputting a value for n.
    Code:
    int x, y;main()
    {printf("\nInput an integer value for x:");  
      scanf("%d",  &x);   
    
    printf("\nInput an integer value for y:");   
    scanf(" %d",  &y);        
           if (x==y) 
             printf("x is equal to y");   
           if (x>y)   
             printf("x is greater than y");          
           if (x<y) 
             printf("x is less than y"); 
      
     return 0; 
    }

    This is an example from my book, and it doesn't work.....how frustrating
    Such that before I input a value, this is displayed as the output
    Code:
    Input an integer value for x:
    Input an integer value for y:
    x is equal to y

    Why doesn't the complier wait for the scanf user-input before finishing the code?

    Last edited by ProBallChamp; 03-15-2013 at 02:34 PM.

  2. #2
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    When ever I use scanf("%d",n) ; and then have a following printf("Generic Statement: %d", n); My compiler displays the printf statement without me inputting a value for n.
    That's strange. Compilers usually translate code from one language to another.

    This is an example from my book, and it doesn't work.....how frustrating
    You should get a better book like K&R2. Unless you understand buffering, it's not a good idea to try to synchronise data on two 'interactive' streams.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The book is OK. Your keyboarding has left you adrift.

    Code:
    //When ever I use 
    scanf("%d",n) ;  //you forgot the ampersand: scanf("%d",&n);
    
    //and then have a following 
    printf("Generic Statement: %d", n); //you forgot the name of the variable: printf"Generic Statement: %d\n",INT VARIABLE NAME HERE);
    It's a good habit to put a \n on the very end of all printf() statements - some systems have a buffer for it, and it will drive a programmer bonkers!

  4. #4
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    Quote Originally Posted by Adak View Post
    The book is OK.
    Err, no. Why do x and y need static storage duration other than to stop your program from breaking when scanf fails?

    It's a good habit to put a \n on the very end of all printf() statements - some systems have a buffer for it, and it will drive a programmer bonkers!
    I'm not sure what you mean by "some systems have a buffer for it". His code doesn't take into consideration that stdout may be line buffered when connected to an interactive device, and that can be fixed either by writing a new line to stdout or calling fflush.

  5. #5
    Registered User
    Join Date
    Mar 2013
    Posts
    9
    I forgot to include that ampersand in the forum text.... whoops

    Quote Originally Posted by Adak View Post
    The book is OK. Your keyboarding has left you adrift.

    Code:
    //When ever I use 
    scanf("%d",n) ;  //you forgot the ampersand: scanf("%d",&n);
    
    //and then have a following 
    printf("Generic Statement: %d", n); //you forgot the name of the variable: printf"Generic Statement: %d\n",INT VARIABLE NAME HERE);
    It's a good habit to put a \n on the very end of all printf() statements - some systems have a buffer for it, and it will drive a programmer bonkers!

  6. #6
    Registered User
    Join Date
    Mar 2013
    Posts
    9
    One caveat to this: When I enter a value for x and y respectively; the correct printf statement will appear. However, this is only true after I see the odd premature printf display as noted in the original post

    Quote Originally Posted by ProBallChamp View Post
    When ever I use scanf("%d",n) ; and then have a following printf("Generic Statement: %d", &n); My compiler displays the printf statement without me inputting a value for n.
    Code:
    int x, y;main()
    {printf("\nInput an integer value for x:");  
      scanf("%d",  &x);   
    
    printf("\nInput an integer value for y:");   
    scanf(" %d",  &y);        
           if (x==y) 
             printf("x is equal to y");   
           if (x>y)   
             printf("x is greater than y");          
           if (x<y) 
             printf("x is less than y"); 
      
     return 0; 
    }

    This is an example from my book, and it doesn't work.....how frustrating
    Last edited by ProBallChamp; 03-15-2013 at 02:36 PM.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    There is nothing in that code which will cause a "premature printf display". Unless your expectations are wrong.

    Try providing a exact description of the input you are supplying when you run the program, and the results you get.

    We're not mindreaders, you know.

    A couple of minor points unrelated to your problem

    1) It is a good idea for there to be a #include <stdio.h> as the first line.

    2) Explicitly give main an int return type. Yes, I know some books tell you the compiler assumes that anyway, but it's a bad habit for a programmer to rely on that, roughly on the level with you picking your nose and eating it.

    3) The compiler does not display printf() statements. Your program does.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    This comes from a review of a book, actually, which is irrelevant unless you are reading that book, but it contains the best explanation of the problem I think you are experiencing now that I have ever seen.

    As you should know, C is a standardized language --
    Schildt frequently omits trailing newlines on output. This is a common habit among DOS programmers, as the MS-DOS command prompt apparently used to start with a newline, so that programs which had already produced a newline were followed by a blank line.

    However, it's not portable, in two ways. The first is that, in general, C does not define the behavior of output to a text stream which is never terminated by a newline. ("Whether the last line requires a terminating new-line character is implementation-defined."; C99, 7.19.2, paragraph 2.)

    The second is that streams may be buffered -- output sent to a stream may not be delivered to the host environment until flushed (using fflush()) or until some other event occurs. There are three levels of buffering; unbuffered (self-explanatory), line-buffered (data are buffered until a new-line character is encountered), or fully buffered (data are buffered until a certain size of block is filled, such as "every 8,192 bytes".) The standard input and output streams are very often line-buffered, although the standard does not require this; all it says that standard input and standard output are "fully buffered if and only if the stream can be determined not to refer to an interactive device." (C99, 7.19.3, paragraph 7).

    What this means is that, on many systems, printing a prompt which does not end with a newline produces no visible output until you either explicitly flush the stream or send something ending in a newline. (There may be other circumstances under which output is sent, but only those are guaranteed to deliver the output to the host environment.) One common exception is that some systems will automatically flush output streams when waiting for input; on such systems, the prompt would actually get displayed. This behavior is strongly recommended by C99.
    C: The Complete Nonsense

  9. #9
    Registered User
    Join Date
    Mar 2013
    Posts
    9
    Here is as far a I know how to go (since I am new to the C programming language)
    Code:
    #include <stdio.h>
    #include <math.h>
    int x, y;
     main()
    {    printf("\nInput an integer value for x:");
          scanf("%d", &x);
          printf("\nInput an integer value for y:");    
          scanf(" %d", &y);
             if (x==y) 
              printf("\nx is equal to y");
            if (x>y)
               printf("\nx is greater than y");
            if (x<y)
               printf("\nx is less than y\n");
        return 0;}
    
    The output is as such
    Code:
    Input an integer value for x:
    Input an integer value for y:
    x is equal to y
    How can I prevent "x is equal to y"from being displayed prior to me inputting anything?

    Quote Originally Posted by grumpy View Post
    There is nothing in that code which will cause a "premature printf display". Unless your expectations are wrong.

    Try providing a exact description of the input you are supplying when you run the program, and the results you get.

    We're not mindreaders, you know.

    A couple of minor points unrelated to your problem

    1) It is a good idea for there to be a #include <stdio.h> as the first line.

    2) Explicitly give main an int return type. Yes, I know some books tell you the compiler assumes that anyway, but it's a bad habit for a programmer to rely on that, roughly on the level with you picking your nose and eating it.

    3) The compiler does not display printf() statements. Your program does.

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    As I said before .....
    Quote Originally Posted by grumpy View Post
    Try providing a exact description of the input you are supplying when you run the program, and the results you get.
    You have described the output repeatedly but provided absolutely NO DESCRIPTION of the INPUT you are supplying. In your program, the input affects the output.

    Does it include digits? Does it include whitespace (spaces, carriage returns, etc)? Does it include other characters?


    The text that whiteflags quoted is interesting, but would not explain "premature" output ..... it would explain output coming AFTER you would expect.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  11. #11
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    Try seeing how this performs:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        int x, y;
    
        puts("enter two values; the value of x, followed by the value of y");
        if (scanf("%d %d", &x, &y) != 2)
            return EXIT_FAILURE;
        printf("%d %d\n", x, y);
        return 0;
    }
    edit: BTW, chances are you're entering something that can't be converted by scanf, causing it to fail on both accounts and immediately proceed through the program. Since you've statically allocated x and y, they'll both have an initial value of 0, causing them to be equal if a value doesn't get stored in them by scanf. That's usually the kind of behaviour you'd expect when you ignore its return value.
    Last edited by Barney McGrew; 03-15-2013 at 05:01 PM.

  12. #12
    Registered User
    Join Date
    Dec 2012
    Posts
    307
    ok this is what i see.

    Code:
    int x,y;
    you have it set as global, instead that should go after
    Code:
    main()
    {
    also
    Code:
    main()
    is very bad. seeing your using the return right
    change your main to
    Code:
    int main(void)
    it is better practice, and some new compiliers yell at you if you dont!

    also you dont need to include math.h, as your really not using anything from the math header

    now in the end, even without these changes, the code runs on my pelles c ide

    after those "fixes" whatever compilier your using should accept it and run it right.

    if not, turn UP all the warnings and error notifications and maybe it will warn you what is wrong.

  13. #13
    Registered User
    Join Date
    Mar 2013
    Posts
    9
    Okay, I see what you are looking for, here are three working cases when I input a x and y respectively;
    1)
    Input:
    Code:
    5   /* x  */
    4  /* y  */
    Output
    Code:
    Input an integer value for x:
    Input an integer value for y:
    x is greater than y
    2)
    Input:
    Code:
    4
    5
    Output
    Code:
    Input an integer value for x:
    Input an integer value for y:
    x is less than y
    3)
    Input:
    Code:
    5
    5
    Output
    Code:
    Input an integer value for x:
    Input an integer value for y:
    x is equal to y

    Quote Originally Posted by grumpy View Post
    As I said before .....

    You have described the output repeatedly but provided absolutely NO DESCRIPTION of the INPUT you are supplying. In your program, the input affects the output.

    Does it include digits? Does it include whitespace (spaces, carriage returns, etc)? Does it include other characters?


    The text that whiteflags quoted is interesting, but would not explain "premature" output ..... it would explain output coming AFTER you would expect.

  14. #14
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    So what's the problem?

  15. #15
    Registered User
    Join Date
    Mar 2013
    Posts
    9
    Crossfire Could you clarify this for me.
    Code:
    int main(void){int x, y;
    So the above is not redundant; saying integer main and integer variable x and y?

    also what does the main(void) mean/do?

    Quote Originally Posted by Crossfire View Post
    ok this is what i see.

    Code:
    int x,y;
    you have it set as global, instead that should go after
    Code:
    main()
    {
    also
    Code:
    main()
    is very bad. seeing your using the return right
    change your main to
    Code:
    int main(void)
    it is better practice, and some new compiliers yell at you if you dont!

    also you dont need to include math.h, as your really not using anything from the math header

    now in the end, even without these changes, the code runs on my pelles c ide

    after those "fixes" whatever compilier your using should accept it and run it right.

    if not, turn UP all the warnings and error notifications and maybe it will warn you what is wrong.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Easy scanf() question
    By Roger in forum C Programming
    Replies: 3
    Last Post: 11-05-2009, 06:35 PM
  2. Replies: 23
    Last Post: 04-20-2009, 07:35 AM
  3. Seg fault in easy, easy code
    By lisa1901 in forum C++ Programming
    Replies: 11
    Last Post: 12-10-2007, 05:28 AM
  4. scanf trouble
    By sloke in forum C++ Programming
    Replies: 4
    Last Post: 11-16-2005, 03:31 PM
  5. Having trouble with scanf function
    By cw3od in forum C Programming
    Replies: 2
    Last Post: 11-28-2001, 03:58 PM

Tags for this Thread