Home > OS >  Trying to get a specific output for three wrong answers only in C
Trying to get a specific output for three wrong answers only in C

Time:06-08

I'm trying to get my program to print "stop answering wrong freak" after answering no three times, but I can't seem to get my while loop to achieve this, if anyone could help, I'm a super beginner so any tips would be appreciated.

I was trying to increase the counter x each time for no, then if you answer no wrong again the while loop ends and the other message appears.

Thanks so much.

    char n[20];
    int x = 0;

    do {
        printf("Are you cool yes/no ? ");
        scanf("s", n);

        if (strcmp(n, "yes") == 0) {
            printf("%s is the correct answer, i can only be friends with cool people\n", n);
            break;
        } else
            x  , printf("%s is the wrong answer, i only like cool people sorry!\n", n);
    } while (!strcmp(n, "yes") && x < 3);
    printf("stop answering wrong freak!\n");
    break;

CodePudding user response:

Don't use a do / while loop, use a for ever loop and break appropriately:

    for (int x = 0;;) {
        char n[20];
        printf("Are you cool yes/no ? ");
        if (scanf("s", n) != 1) {
            printf("end of file already? I don't like leavers\n");
            break;
        }
        if (strcmp(n, "yes") == 0) {
            printf("%s is the correct answer, I can only be friends with cool people\n", n);
            break;
        }
        printf("%s is the wrong answer, I only like cool people sorry!\n", n);
        if (  x == 3) {
            printf("I am not listening to you anymore!\n");
            break;
        }
    }

CodePudding user response:

Your code has most of the logic right but just needs a few tweaks to do what you have asked.

Like Weather Vane mentioned, there is no need to test using strcmp each iteration of the while loop, you are already doing that within your if statement. You only need to check to make sure that x is still within the limit that you decided, 3.

Lastly, when your program finishes, you need to make sure that the printf statement for non-cool people is not printed for cool people, by adding an if statement like so:

if(x == 3)
{
    printf("stop answering wrong freak!\n");
}

So your complete code would be this:

#include <stdio.h>

int main()
{
    char n[20];
    int x = 0;

    do {
        printf("Are you cool yes/no ? ");
        scanf("s", n);

        if (strcmp(n, "yes") == 0)
        {
            printf("%s is the correct answer, i can only be friends with cool people\n", n);
            break;
        }
        else
        {
            x  , printf("%s is the wrong answer, i only like cool people sorry!\n", n);
        }
    } while (x < 3);
    
    if(x == 3)
    {
        printf("stop answering wrong freak!\n");
    }
}
  •  Tags:  
  • c
  • Related