Search code examples
c++cbuffergetcharputchar

getchar() or putchar() keeps eating the first character of my input


edit: this question is solved. thank you for all answers

This is my program:

#include <stdio.h>
int main(){

printf("write something : \n");
int c = getchar();

while((c = getchar()) != EOF){

if (c == ' ' || c == '\t')
 printf(" \n");
else
  putchar(c)
}
return 0;
}

everytime i run it, it works fine, but eats the first character of my input for example when i run the program the output looks like this:

write something : 
this is a sentence.
his 
is
a
sentence.

the "t" is missing. why is that happening and how can i fix it?

thank you for your time.


Solution

  • You say int c = getchar() which will retrieve "t".
    Then when you say while (c = getchar()) it will retrieve "h", note that you did not even get a chance to print the character out since you called getchar in the while statement.

    To fix this, declare int c = 0; or int c;

    Then when you call getchar() in the while loop you will start at the first character.