Search code examples
cinputscanfgetchar

C: scanf() hanging, getchar() not working to clear input


The function is supposed to prompt a user for input, and then return a value, however it keeps hanging.

#include <stdio.h>

int foo(void) {
    printf("return something ");
    char input;
    scanf("%d", &input);
    while (getchar() != '\n') {}
    printf("input: %d\n", input);
    return input;
}

int main()
{
    int t = foo();
    printf("foo() returned: %d\n", t);
    return 0;
}

OUTPUT

return something 4                                                                                                     
input: 4                                                                                                               
foo() returned: 4                                                                                                      
Segmentation fault                                                                                                     
                                                                                                                       
                                                                                                                       
...Program finished with exit code 139                                                                                 
Press ENTER to exit console.   

I've tried scanf(" %d", &choice) as well, but to no avail. If its relevant, this code is part of something that is eventually compiled into a .o file and then linked to main(), where it's called.


Solution

  • You are reading the input with code %d but you are asking to put it into a variable of type char - that variable is too small. If you change char input to int input it works: https://ideone.com/KpLH25