简体   繁体   中英

Skipping over Scanf statement in C

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 replicate the other program exactly, so I went into the other one and entered a character into the wordlength. It came up with the "number must be between 3 and 14 (inclusive)" statement, and asked me to enter a number again, but it started to loop infinitely. It works when i enter a number lower than 3 and larger than 14 (comes up with the error and asks for another input) but with a letter it infinitely loops. Any ideas??? Thanks

while (i == 0){

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

您正在检查number但似乎必须检查wordLength变量,并且(如@Narkha 所指出的)使用break而不是continue退出循环。

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.

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)");
        }
    }

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)");
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM