-1

Can you tell what wrong here?

#include <stdio.h>
#include <stdlib.h>

int test (void)
{
    int i;
    printf("Enter a number: ");
    scanf("%d",&i);

    return i;
}

int main (void)

{

   test();

   return 0;
}

This is just a simple example but for some reason main doesn't run unless I get rid of the scanf.

8
  • 1
    What do you mean by doesn't run? It will be waiting for input, if that's what you mean.
    – chris
    Nov 12, 2012 at 3:16
  • just sits there doing nothing? :) type 1<ENTER> Nov 12, 2012 at 3:17
  • Also try to print something. after scanf(), give input '1' , and add statement printf(). So that you will see your program is good to go.
    – suraj_fale
    Nov 12, 2012 at 3:21
  • 1
    Nothing happens the compiler runs but nothing shows up. It just runs and runs until I forcibly close it. If I comment out the scanf(), at least "Enter a number" will show up.
    – user688604
    Nov 12, 2012 at 3:29
  • I tried typing 1<ENTER> and "Enter a number:" shows up. It's like it's running backwards.
    – user688604
    Nov 12, 2012 at 3:32

2 Answers 2

1

Always use a '\n' at the end of your printf string. This makes the output buffer flush and print the string. Add more prints in your program. You can rewrite your program like following, and the prints will help you understand what is happening with your program.

#include <stdio.h>
#include <stdlib.h>

int test (void)
{
    int i;
    printf("Enter a number: \n");
    scanf("%d",&i);
    printf("You just eneterd : %d\n",i);
    return i;
}

int main (void)

{
   printf("About to call test() \n");
   test();
   printf("Done calling test() \n");
   return 0;
}

Better get a good C programming book for understanding these basic stuff. I suggest The C programming language

0
0

I think you must make use of fflush() or making use of a '\n' character at the end of the printf function which will eventually flush the std output buffer. For checking just make use of the printf() for printing the value of the variable just after reading the value.

Hope that helps....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.