繁体   English   中英

getchar() 并逐行读取

[英]getchar() and reading line by line

对于我的一个练习,我们需要逐行阅读并仅使用 getchar 和 printf 进行输出。 我正在关注 K&R,其中一个示例显示了使用 getchar 和 putchar。 根据我的阅读,getchar() 一次读取一个字符,直到 EOF。 我想要做的是一次读取一个字符直到行尾,但将写入的所有内容存储到 char 变量中。 所以如果输入 Hello, World,. 它还会将其全部存储在一个变量中。 我试过使用 strstr 和 strcat 但没有成功。

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

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

#define MAX_LINE 256
char line[MAX_LINE];
int c, 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 稍后会教你动态分配内存,你可以用它来读取任意长的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM