Home > Net >  Why does my c code repeat the first printf line?
Why does my c code repeat the first printf line?

Time:04-01

I want an infinite loop and that's working. But I don't know why it prints out the same line two times. Any thoughts?

The output:

Last choice: p
Your next move: RLast choice: Last choice: l
Last choice: Last choice: r
Your next move: SLast choice: Last choice:

This is my code so far:

#include <stdio.h>
#include <cs50.h>

int main ()
{
    while (true)
    {
// Prompt user for input last choice contender
        char c;
        printf("Last choice: ");
        c = getchar();
      // If last choice is R, loser should play S
        if (c == 'R'|| c == 'r')
        {
            printf("Your next move: S");
        }
// Else if last choice is P, loser should play R
        else if (c == 'P' || c == 'p')
        {
            printf("Your next move: R");
        }
// Else if last choice is S, loser should play P
        else if (c == 'S' || c == 's')
        {
            printf("Your next move: P");
        }
    }
}

CodePudding user response:

It's because when you put your key and then press enter, getchar gets your key right, and it also gets a \n which is your enter key. So you just need to add on a little if in your code to make it work like this:

#include <stdio.h>
#include <cs50.h>

int main ()
{
    while (true)
    {
// Prompt user for input last choice contender
        char c;
        printf("Last choice: ");
        c = getchar();
        if (c != '\n')
            getchar(); //gets the \n if you've given a letter
      // If last choice is R, loser should play S
        if (c == 'R'|| c == 'r')
        {
            printf("Your next move: S");
        }
// Else if last choice is P, loser should play R
        else if (c == 'P' || c == 'p')
        {
            printf("Your next move: R");
        }
// Else if last choice is S, loser should play P
        else if (c == 'S' || c == 's')
        {
            printf("Your next move: P");
        }
    }
}

CodePudding user response:

I think I got it working for you!

#include <stdio.h>
int main () {
    printf("Last choice: ");
    while (1) {
        char c;
        c = getchar();
        if(c != '\n')
        {
            if (c == 'R'|| c == 'r') {
                printf("Your next move: S\n");
            } else if (c == 'P' || c == 'p') {
                printf("Your next move: R\n");
            } else if (c == 'S' || c == 's') {
                printf("Your next move: P\n");
            } else {
                printf("Use valid input\n");
            }
            printf("Last choice: ");
        }
    }
}
  • Related