C question console application windows

C question console application windows

Joeado123
May 29, 2018
Hi, I am doing a plus or minus game (I'm actually learning how to code in c) and I had a problem. When I was typing letter instead of numbers, (The menu is all right it's covered with a switch) I was trying to guess the number I got "It's Bigger!" (this is what I wrote it's normal) but written a thousand times surely. Why is it doing this and how can I write letters without the need to close the program?

» 3 Answers

  • Joeado123
    May 29, 2018
    The case 1 of my switch (might help to know what's missing)


    switch(Menu)
    {
    case 1:
    printf("\nPlus or Minus level 1: between 1 and 100");
    int MAX = 100, MIN = 0;
    srand(time(NULL));
    number1 = (rand() % (MAX - MIN + 1)+ MIN);
    printf("\nType a number between 1 and 100:");
    do
    {
    scanf("%d", &number2);


    if (number1 < number2)
    {
    printf("It's less!");
    meter++;
    }

    else if (number1 > number2)
    {
    printf ("It's more!");
    meter++;
    }

    else
    {
    printf("You found the mystery number in %d times", );
    meter = 0;
    printf("\nDo you want to do another game?\nIf yes type 1, or 0 to quit: ");
    scanf("%d", &Replay);
    }
    }while(number1 != number2);

    break;
  • GerbilSoft
    May 30, 2018
    If you enter a letter, it fails the "%d" specifier, so scanf() returns 0 and doesn't set number2 to anything. You might want to try this instead:

    char buf[128];
    fgets(buf, sizeof(buf), stdin);
    number2 = (int)strtol(buf, NULL, 10);
    
    This uses fgets() to get a string from stdin (up to 127 characters plus NULL terminator), and then uses strtol() to convert it to a number.

    Note that strtol() will return 0 if it's not a valid number.
  • Cyan
    May 30, 2018
    if it still return 0 when an invalid number is entered, he will have the same result.
    maybe he can use isdigit() to verify buf before calling strtol()?

    edit: maybe it can only check one char at a time?