0

I wrote this code for a school project and I have the following problem. When I choose 1 at the first time, my program runs fine but as I choose w or r the second time, something goes wrong. None of the 2 ifs is running. I printed usr_ans2 to see the result of scanf and usr_ans2 variable is a weird question mark in a box and not a w or r character as I typed. Also I tried scanf(" %c", usr_ans2) . The question marks do not appear but the if commands are still not running.

int main(){

    int usr_ans1;
    char usr_ans2;

    while(1){

        printf("\nSelect action: (1-3)\n");
        scanf("%d", &usr_ans1);

        if(usr_ans1 == 1){
            printf("Select to write or read from a file the text: (w/r) ");
            usr_ans2 = scanf("%c", &usr_ans2);

            if(usr_ans2 == 'w')
                printf("You selected to write");

            else if(usr_ans2 == 'r')
                printf("You selected to read");

        }

        else if(usr_ans1 == 2){
            printf("Example1");
        }

        else if(usr_ans1 == 3){
            printf("Example2");
        }

    return 0;
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91
Jimmy
  • 13
  • 1
  • 7
  • You're overwriting the value recorded into `usr_ans2` by assigning the return value of `scanf` to it. – bnaecker Apr 19 '18 at 03:32
  • A side note - even if the `if` result is only one line, please make yourself a good habit and wrap it with brackets. You'll save yourself lots of debugging time this way. – SHG Apr 19 '18 at 03:36
  • Note, that trailing space will not do the exact same thing that space in front, the question is more generally "what space do in format string" – Stargateur Apr 19 '18 at 04:13

1 Answers1

2

scanf() in usr_ans2 = scanf("%c", &usr_ans2); will return 1 (the numbers of successfully converted specifiers) or EOF (some negative value like -1 when end-of-file or error occurs). if(usr_ans2 == 'w') will never be true.

Try

// usr_ans2 = scanf("%c", &usr_ans2);
scanf(" %c", &usr_ans2);  // add the space too to skip leading white-space
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256