一些巧妙地使用指针算术来做你想做的事:
#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
是接受用户输入的推荐方式)。