1
    int main() {
        // insert code here...
        char ch; //the operator
        int c, t, h ; //the weight of the three items
        int flag = 1; //note for iteration ending


        while (flag == 1) { 
            printf("input operator:");
            ch = getchar();
            switch (ch) {
                case 'a':
                    printf("input the weight of chaoxianji:");
                    scanf("%d", &c);
                    break;
                case 'b':
                    printf("input the weight of tiancai:");
                    scanf("%d", &t);
                    break;
                case 'c':
                    printf("input the weight of huluobo:");
                    scanf("%d", &h);
                    break;
                case 'q':
                    flag = 0; // get out of cycle 
                    break;
                }
            }
        return 0;

}

But the output block is : The notion appears twice And I am wondering why the note "input operator appeared twice. 'break' should have bring the procedure to the printf statement ,shouldn't they?

Leo Li
  • 81
  • 1
  • 7
  • 3
    This may be the most common question at SO, and has been answered many, many times. `scanf()` is leaving a `\n` character in the input stream, and the call to `getchar()` is picking it up instead of the expected operator character. – ad absurdum Feb 06 '18 at 04:20
  • Don't mix different input methodologies. If you're going to use `scanf`, then use `scanf` for everything. In other words, `ch = getchar();` should be `scanf(" %c", &ch);`. (The space in front of the `%` is important. That's the second most common question.) – user3386109 Feb 06 '18 at 04:29
  • And the third most common question. Always check the return value from every library function you call. Because if the library function fails, and you don't handle the error, then your code is going to crash and burn. Which is to say that `scanf(" %c", &ch)` should be `if (scanf(" %c", &ch) != 1) { handle_the_error(); }` – user3386109 Feb 06 '18 at 04:35
  • THX for the coding details! It does work when I add the space to %c! But why did that work? – Leo Li Feb 06 '18 at 04:38
  • @LeoLi I added a link above the question that answers that. – user3386109 Feb 06 '18 at 04:41

0 Answers0