我是初学者,正在学习 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 , strcpy和 strlen .请务必查看它们,因为它们是非常有用的函数(fgets
是接受用户输入的推荐方式)。
关于c - 通过 getchar 和 putchar 打印多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17717850/