Search code examples
cscanfstdio

Why can't my C program complete the code after inputing a number?


I just started learning C so I have no idea why this is happening.

#include <stdio.h>

int square(int x);

int main(int argc, const char * argv[])
{
    printf("Enter a number");
    int userNum;
    scanf("%d", &userNum);
    int result = square(userNum);
    printf("The result is %d", result);

}

int square(int x){
    int result = x*x;
    return result;
}

It would ask for a number but then nothing would happen after I input. If I were to take the scanf out and put square(10) or something, the code will run and finish.


Solution

  • It compiles and runs as expected for me using both gcc and clang... to make it more clear (as maybe other text is getting in your way of seeing the answer) add new lines to what you are outputting to stdout:

    int main( void ) {
        printf("Enter a number: ");
    
        int userNum;
    
        scanf("%d", &userNum);
    
        int result = square(userNum);
    
        printf("\nThe result is: %d\n", result);
    
        return 0;
    }
    

    If you are testing in terminal (and not piping input) then recall that scanf (with the %d placeholder) will read an integer until the next character that is not a numerical character. So on your keyboard you will need to type 10 and return (or enter). Otherwise, pipe your program an input file:

    10
    

    ... using the following command:

    ./a.out < input.txt