1

As long as the input is not x, the loop will continue to ask for the input and it prints out either A or B.

int main (void){

    char input;

    while( input != 'x'){

        printf("Enter Input:");

        scanf("%c", &input);

        if (input == 'a'){

            printf("A \n");
        }

        else{

            printf("B\n");
        }

   }

    return (0);
}

The problem is that everytime after i entered the input, it prints the output and it also prints out "Enter Input:B" in a new line no matter i entered a or b or anything else as input. Can anyone tell me how can i solve this problem, Thanks!

Here is what happened:

Enter Input:a

A

Enter Input:B /after the output it always prints this line, how can i get rid of it??/

Enter Input:a

A

Enter Input:B

Enter Input:b

B

Enter Input:B

Enter Input:b

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
user1068755
  • 11
  • 1
  • 1
  • 3

3 Answers3

4

In order to ignore newlines, the scanf should likely be:

scanf(" %c", &input);
       ^

Also you probably want to flush stdout right after that printf:

printf("Enter Input:");
fflush(stdout);
cnicutar
  • 178,505
  • 25
  • 365
  • 392
1

You need to eat a newline char:

scanf("%c", &input);
  while((ch=getchar())!='\n');
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
0

The error is because the newline character is read from input.

You can refer to this one too : Why doesn't getchar() wait for me to press enter after scanf()?

Community
  • 1
  • 1
Lunar Mushrooms
  • 8,358
  • 18
  • 66
  • 88