c - 通过 getchar 和 putchar 打印多行

标签 c input output getchar putchar

我是初学者,正在学习 C 编程语言并使用 Microsoft Visual C++ 编写和测试代码。

下面的文本中的 C 程序(第 1.5.1 节)通过 putchar() 和 getchar() 将其输入复制到其输出:

#include <stdio.h>
int main(void)
{   int c;
    while ((c = getchar()) != EOF)
         putchar(c);
    return 0;}

程序每次按回车都会打印键盘输入的字符,结果只能输入一行再打印。我找不到在打印前通过键盘输入多行文本的方法。

有什么方法和方法可以让这个程序从键盘输入和输出多行文本吗?

抱歉,如果这是一个基本且无知的问题。

感谢您的关注并提前致谢。

最佳答案

巧妙地使用指针算法来做你想做的事:

#include <stdio.h>  /* this is for printf and fgets */
#include <string.h> /* this is for strcpy and strlen */
#define SIZE 255 /* using something like SIZE is nicer than just magic numbers */

int main()
{
    char input_buffer[SIZE];        /* this will take user input */
    char output_buffer[SIZE * 4];   /* as we will be storing multiple lines let's make this big enough */

    int offset = 0; /* we will be storing the input at different offsets in the output buffer */

    /* NULL is for error checking, if user enters only a new line, input is terminated */
    while(fgets(input_buffer, SIZE, stdin) != NULL && input_buffer[0] != '\n') 
    {
        strcpy(output_buffer + offset, input_buffer); /* copy input at offset into output */
        offset += strlen(input_buffer);               /* advance the offset by the length of the string */
    }

    printf("%s", output_buffer); /* print our input */

    return 0;
}

这就是我使用它的方式:

$ ./a.out 
adas
asdasdsa
adsa

adas
asdasdsa
adsa

一切都被鹦鹉学舌了:)

我用过 fgets , strcpystrlen .请务必查看它们,因为它们是非常有用的函数(fgets 是接受用户输入的推荐方式)。

关于c - 通过 getchar 和 putchar 打印多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17717850/

相关文章:

c - 字符串中间的 '\0'在C中能被识别为字符串的结尾吗?

javascript - HTML 框格式

layout - 在 Lisp 中打印列中的嵌套列表

c++ - CodeBlocks C++ 输出文件

c - 使用 DFS 计算连接 block 的结果错误

c - 如何在没有递归但只有循环的情况下实现合并排序?

c - 具有链表内存转储的结构

c - 指针太困惑了 : Stack with singly linked list in C

css - 如何设置必填字段的样式(仅在单击时)

twitter-bootstrap - Bootstrap 4 自定义文件上传和调整大小