getchar() 并逐行读取

发布于 2024-10-16 04:38:31 字数 332 浏览 2 评论 0原文

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

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

For one of my exercises, we're required to read line by line and outputting using ONLY getchar and printf. I'm following K&R and one of the examples shows using getchar and putchar. From what I read, getchar() reads one char at a time until EOF. What I want to do is to read one char at a time until end of line but store whatever is written into char variable. So if input Hello, World!, it will store it all in a variable as well. I've tried to use strstr and strcat but with no sucess.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆悲凉 2024-10-23 04:38:31

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

#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 稍后将教您动态分配内存,您可以使用它来读取任意长的行。

You will need more than one char to store a line. Use e.g. an array of chars, like so:

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

With this, you can't read lines longer than a fixed size (255 in this case). K&R will teach you dynamically allocated memory later on that you could use to read arbitarly long lines.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文