0

I have recently started learning I/O file operations in C. And in this code I am facing an issue the while loop is not exiting even when I put nonwhite space character ' ' . Plz, tell me where I am wrong and how to exit while loop.

#include <stdio.h>
int main()
{
  char a = 0;
  while ((a = (char)getchar()) != ' ');
  ungetc(a, stdin);
  printf("\n Value of A is  %c", a);
  return 0;
}

1 Answer 1

2

The getchar function returns an int for a reason. It can either return a character if there is one, or EOF to indicate the end of your input stream. So using a char variable to store the result is not a good idea.

Then, you should also always test for EOF and act accordingly if you encounter this condition.

Also, usually these streams are line buffered, so you woudn't see any input until you enter a whole line.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.