Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

Printing the input of char within a loop in C

Suppose char c is an input of single character from user.

if (c != 'A' && c != 'B' &&  c != 'C' && c != 'D') {
    int t = 1;
    while (t = 1) {
    printf("%c is an invalid input. Valid cases are A-D.
", c);
    scanf( "%c", &input); /* Space for taking care of whitespace */
    c = lowToUp(c); /* If c is lowercase, convert to uppercase */
    if (c == 'A' || c == 'B' || c == 'C' || c == 'D') {
      break;
    }
  }
}

I'm trying to display this error message and continue the loop until user inputs valid char value.

The loop itself is fine but the output is not. If I enter X,

X is an invalid input. Valid cases are A-D.

 is an invalid input. Valid cases are A-D.

The invisible after the actual value of c has not bothered me in any other part of my program except this one.

How do I get rid of it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After each scanf, you need to flush the input buffer. E.g.:

int c;
....
scanf (....)
do { c = getchar (); } while (c != '
' && c != EOF);     /* flush input buffer */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...