通过getchar和putchar打印多行 [英] print multiple lines by getchar and putchar
问题描述
我是初学者,学习C编程语言,并使用Microsoft Visual C ++编写和测试代码.
Im a beginner learning The C Programming language and using Microsoft visual C++ to write and test code.
在C中的程序中,文本(第1.5.1节)通过putchar()和getchar()将其输入复制到其输出:
Below program in C from text(section 1.5.1) copy its input to its output through putchar() and getchar():
#include <stdio.h>
int main(void)
{ int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;}
程序每次按ENTER键都会打印键盘输入的字符.结果,我只能在打印前输入一行.我找不到在打印之前通过键盘输入多行文本的方法.
The program print characters entered by keyboard every time pressing ENTER.As a result,I can only enter one line before printing. I can't find a way to enter multi-line text by keyboard before printing.
有什么方法以及如何让该程序从键盘输入和输出多行文本?
Is there any way and how to let this program input and output multi-line text from keyboard?
很抱歉,这是一个基本且无知的问题.
Sorry if this is a basic and ignorant question.
提前感谢您的关注和感谢.
Appreciate your attention and thanks in advance.
推荐答案
一些巧妙地使用指针算法来做自己想要做的事情:
Some clever use of pointer arithmetic to do what you want:
#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 , strlen .请仔细检查这些功能,因为它们是非常有用的功能(建议使用fgets
进行用户输入).
I've used fgets, strcpy and strlen. Do look those up as they are very useful functions (and fgets
is the recommended way to take user input).
这篇关于通过getchar和putchar打印多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!