getchar() skips every other char in C

故事扮演 提交于 2019-12-20 07:28:03

问题


I have been having problems fully using getchar() for a while now in C. And in this case I am trying to read a line and put the char's of the line into an array. However upon assigning the getchar() to the array it skips some characters.

For example the input "It skips every other" the output is...I\n \n k\n p\n \n v\n r\n \n t\n e\n. (the \n is just to represent the new line.)

int N = 0;

char message[80] = {};

do
{
    message[N] = getchar();
    N++;
    printf("%c\n", message[N-1]);
}
while(getchar() != '\n');

Thank you for your time, as stated before almost anytime I have ever tried to use getchar() it always gives some unexpected result. I don't fully understand how the function reads the char's.


回答1:


You're calling getchar() twice one in the while condition and other inside the do-while body.

Try this code instead:

int N = 0;
#define MAX_SIZE 80

char message[MAX_SIZE] = {};
char lastChar;

do
{
    lastChar = getchar();  
    if (lastChar == '\n')
        break; 
    message[N] = lastChar;
    N++;
    printf("%c\n", message[N-1]);
}
while(N < MAX_SIZE);

UPDATE: Added checks for maximum size of the array instead of using an infinite do-while loop.




回答2:


You're calling getchar() twice every time through the loop. Each time you call getchar() it consumes one character. So instead of calling getchar() in your while( ... ) condition, compare the value of message[N] to the newline character.



来源:https://stackoverflow.com/questions/15105926/getchar-skips-every-other-char-in-c

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