c - getchar() 并逐行读取

标签 c getchar

对于我的一个练习,我们需要逐行阅读并仅使用 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 稍后会教你动态分配内存,你可以用它来读取任意长的行。

关于c - getchar() 并逐行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4909009/

相关文章:

c - printf 没有打印出预期的结果,为什么?

c - 在某些特定情况下访问数组时出现运行时错误

c - 为什么这个 boolean 值没有给我正确的值?

c - return 的简化版本 ((union { float v; uint32_t r; }){(int)x}.r>>21) - 496

c - 在同一行中包含 Ctrl+Z 后,getchar() 继续接受输入

c - getchar() 忽略空格

console - 类似于 getchar 的功能

c - 为什么只有当可执行文件在 Visual Studio 下运行时 CreateFileA 才会失败?

c - 位运算 - 表示有符号整数的符号

在 C 中使用递归创建二叉树