getchar()跳过C中的所有其他char

我在C中完全使用getchar()已经有一段时间了。在这种情况下,我试图读取一行并将该行的char放入数组中。 但是,在将getchar()分配给数组时,它会跳过一些字符。

例如,输入“它会相互跳过”,输出是…… \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n (\ n只是代表新行。)

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

感谢您的时间,如前所述,几乎在我尝试使用getchar()时,它总会给出一些意想不到的结果。 我不完全理解该函数如何读取char。

你在while条件下调用getchar()两次,在do-while体内调用其他函数。

请尝试使用此代码:

 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); 

更新:添加了对数组最大大小的检查,而不是使用无限的do-while循环。

你每次通过循环调用getchar()两次。 每次调用getchar()它都会消耗一个字符。 因此,不要在while( ... )条件中调用getchar() ,而是将message[N]的值与换行符进行比较。