O
O
OccamaRazor2016-09-03 20:26:57
Programming
OccamaRazor, 2016-09-03 20:26:57

How to fix the "while" loop so that one value is displayed ignoring the line break?

int main(void)
{
  printf(" Type :");
  char i= getchar();
  
  while (i != 'A' && i != 'B' && i != 'C')
  {
    printf("\nYou choose incorrect type, please repeat...\nEnter r type :");
    i= getchar();
   }


}

Result :
You choose incorrect type, please repeat...
Enter r type:
You choose incorrect type, please repeat...
Enter r type:( input space )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2016-09-03
@Mercury13

Correct the line like this...
and see what happens in place of %c...
Can you explain the effect yourself?
And how to count a character in interactive work? I would write my own function that reads the character and everything that was buffered behind it right up to the line feed.

A
abcd0x00, 2016-09-05
@abcd0x00

When you enter a character, you need to press <return> (Enter). So this one leads to the fact that the newline character \n is immediately sent after the entered character. In the next step of the loop, it is read and processed as a regular character, so a skip is obtained.
How it is solved: you need to make the input_char () function.
You need to read the string to the end, and then select the first character from the read string. You can use fgets() to read a string, and sscanf() can be used to read a character from the resulting character array. This is the fgets() + sscanf() way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question