Skipping over Scanf statement in C

后端 未结 4 1725
别那么骄傲
别那么骄傲 2021-01-29 15:50

I am writing an objective c program for hangman. I need to replicate another program which has been given to me. I have done most of it, but am having an issue. It has to replic

相关标签:
4条回答
  • 2021-01-29 16:33

    You are checking number but seems that you must check wordLength variable, and (as pointed out by @Narkha) use break instead of continue to exit from loop.

    0 讨论(0)
  • 2021-01-29 16:35

    Use getchar() after scanf() for avoid newline character left in stdin.

    while (i == 0){
    
                printf("\n\n > Please enter a word length: ");
                    scanf("%d", &wordLength);
                    getchar();
                printf("\n\n");
                if (number > 3 && number < 14) {
                    break;
                }
                else printf("number must be between 3 and 14 (inclusive)");
                }
    
    0 讨论(0)
  • 2021-01-29 16:45

    The loop continue because you are never altering i and i = 0 is altways true; continue make that the code jump to the loop condicion, no end the loop. Also, as @AlterMann comments, you are not checking wordLength, i suggest this

        bool continueLoop = true;
        while (continueLoop ){
            printf("\n\n > Please enter a word length: ");
            scanf("%i", &wordLength);
            printf("\n\n");
    
            if (wordLength > 3 && wordLength < 14) {
                continueLoop  = false;
            }
            else {
                printf("number must be between 3 and 14 (inclusive)");
            }
        }
    

    Or maybe use break and end the loop without flags

        while (true){
            printf("\n\n > Please enter a word length: ");
            scanf("%i", &wordLength);
            printf("\n\n");
    
            if (wordLength > 3 && wordLength < 14) {
                break;
            }
            else {
                printf("number must be between 3 and 14 (inclusive)");
            }
        }
    
    0 讨论(0)
  • 2021-01-29 16:55

    while (i == 0) will loop as long as i stays at value 0. I don't see i being modified anywhere in your code, so there's probably a bug.

    Edit: Alter Mann's answer is even better.

    0 讨论(0)
提交回复
热议问题