简体   繁体   中英

Why this Ansi C program does not give result?

I am using ubuntu 12.04 lts with gcc. This ANSI C code has no error or warning when it is compiled, but when i try to execute a.out file, some junk values appear. Can anyone tell me, what is wrong with this program?

#include <stdio.h>

int get_int(void);

int main (void)
{
    int ret;
    ret = get_int ;
    putchar(ret);
    printf("\n");
    return 0 ;
}

int get_int(void)
{
    int input;
    char ch;
    while ((scanf("%d", &input)) != 1)
    {
        while ((ch = getchar()) != '\n')
          putchar(ch); 

        printf(" is not an integer.\nPlease enter an ");
        printf("integer value, such as 25, -178, or 3: ");

    }
    return input;
}

You're missing parentheses in your function call. This:

ret = get_int ;

should be:

ret = get_int();

Also, both getchar() and putchar() deal in int , not char .

If your compiler isn't warning you about these things, particularly the first one, then either you need a new one, or you need to turn the warning levels on it up.

Also, as Gangadhar points out, right now you're reading in an integer and printing it out as a character, so entering 68 will output D , for instance, on a system that uses ASCII. This may be, but probably isn't, the behavior you want, so replace your putchar() with a call to printf() if it isn't.

These Below two statements are not correct

  ret = get_int ;
  putchar(ret);  

correct them as below

    ret = get_int () ;
   printf("%d\n", ret);

in the above ret =get_int ; this says compiler to store the pointer into an integer(the function name it self points to function) And at that place you need to make call to function.here your function did not take require any arguments so your call should have Empty parenthesis preceded by function name. and the second one is you are using putchar function to print integer value.you need to use printf with %d specifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM