0

If you type a string into a this script,the program will go completely nuts and stay like that.My program first makes two integers,one for the passcode and one for the guess amount.Then it asks to type in your guess.Since you have made a guess, it adds one number to the guessamount integer. But if you have made a guess higher than 100,it takes the one back and tells you,that you have made the mistake.Then it enters to the while loop.If your guess isn't 43, it loops.In the loop,it tells you that you have done it wrong and you can enter your guess.It of course adds another number to the guessamount variable.The same previously mentioned if command is used, to rule out numbers higher than 100.Then if you have it right, it tells you that it was true and tells you the amount of tries.I have used every single possible solution, but none of them have worked.I am just new to C programming and I would really appreciate if you could help me.

#include <stdio.h>
#include <stdlib.h>




int main()
{
    int passcode;
    int guessamount = 0;
    printf("Try to guess the magic passcode:");
    scanf("%d", &passcode);
    guessamount++;
    if(passcode >= 101){
        printf("The passcode is too high!It cannot exceed 100\n");
        guessamount = guessamount - 1;
    }
    while(passcode != 43){
        printf("The passcode was wrong.Please try again:");
        scanf("%d", &passcode);
        passcode = (int)passcode;
        guessamount++;
        if(passcode >= 101){
            printf("The passcode is too high!It cannot exceed 100\n");
            guessamount = guessamount - 1;
        }
    }
    printf("The passcode is true!You used %d tries!", guessamount);



    return 0;
}
  • What do you mean by "goes nuts"? Please show an example run. – Code-Apprentice Mar 01 '19 at 17:10
  • 2
    When `scanf` fails, you have to consume the input buffer to get past the bad chars. [Why is scanf() causing infinite loop in this code?](//stackoverflow.com/q/1716013) – 001 Mar 01 '19 at 17:11
  • And you just learned *why* `scan()` returns the number of fields it converted. And also *why* you're supposed to check that return value. – Andrew Henle Mar 01 '19 at 17:17

1 Answers1

0

When scanf fails, it doesn't consume the input, so you'll be blocked in a infinite loop.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int passcode;
    int guessamount = 0;

    printf("Try to guess the magic passcode:");
    scanf("%d", &passcode);

    guessamount++;

    while (passcode != 43) {
        if (passcode >= 101) {
            printf("The passcode is too high!It cannot exceed 100\n");
            guessamount--;
        }

        printf("The passcode was wrong.Please try again:");
        if (!scanf("%d", &passcode)) {
            printf("Invalid value\n");
            while (getchar() != '\n');
        }

        guessamount++;
    }
    printf("The passcode is true!You used %d tries!", guessamount);



    return 0;
}
Vitor SRG
  • 664
  • 8
  • 9