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

狂风中的少年 提交于 2019-12-08 12:37:25

问题


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.


回答1:


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.




回答2:


In the line

int c = getchar()

you get the value of 't'. however when you call

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

getchar is called again and the 'h' is read. you then putchar for the first time after that. So in summary: you call getchar twice before calling putchar. a solution to this would be to call

int c = getchar();
putchar(c);

at the top



来源:https://stackoverflow.com/questions/23572964/getchar-or-putchar-keeps-eating-the-first-character-of-my-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!