getchar()并逐行阅读

对于我的一个练习,我们需要逐行阅读并使用ONLY getchar和printf输出。 我正在关注K&R,其中一个例子显示使用getchar和putchar。 从我读到的,getchar()一次读取一个char,直到EOF。 我想要做的是一次读取一个字符,直到行结束,但存储写入char变量的任何内容。 因此,如果输入Hello,World!,它也会将它全部存储在变量中。 我试过使用strstr和strcat但没有成功。

while ((c = getchar()) != EOF) { printf ("%c", c); } return 0; 

您将需要多个字符来存储一行。 使用例如一系列字符,如下所示:

 #define MAX_LINE 256 char line[MAX_LINE]; int line_length = 0; //loop until getchar() returns eof //check that we don't exceed the line array , - 1 to make room //for the nul terminator while ((c = getchar()) != EOF && line_length < MAX_LINE - 1) { line[line_length] = c; line_length++; //the above 2 lines could be combined more idiomatically as: // line[line_length++] = c; } //terminate the array, so it can be used as a string line[line_length] = 0; printf("%s\n",line); return 0; 

这样,您就无法读取超过固定大小的行(在本例中为255)。 K&R将在以后教您动态分配的内存,您可以使用它来读取任意长行。