我昨天写了这段代码。我的目标是: 我要求用户输入一个字符串。我将它存储在一个数组中。如果他输入的字符串比数组长度长,那么在屏幕上输出数组中的数组字符后,我会使用 getchar() 输出其余字符,除非遇到换行符。代码在这里:
#include<stdio.h>
#include<malloc.h>
#define BACKUP 20
int main()
{
char *input=NULL;
char rest[BACKUP],c;
input= malloc(sizeof(char)*20);
printf("%lu",sizeof(input));
int i=0,j=1;
printf("\nEnter a very long string.\n\n>>");
fgets(input, sizeof(input), stdin);
printf("%s",input);
while((rest[i]=getchar())!='\n')
{
i=1;
for(;i<BACKUP;i++)
rest[i]=getchar();
i=0;
for(;i<BACKUP;i++)
printf("%c",rest[i]);
i=0;
}
return 0;
}
问题是,第一个循环进展顺利,但之后它的行为却很奇怪。您能更正一下吗?
如果有其他方法可以解决这个问题就更好了。
我通过getchar()
输出输入区域的所有字符不也是一个解决方案吗?我的意思是,我一开始就不再需要数组了?
我应该将 realloc() 分配给数组,然后输入数组中的其余字符吗?最后,当输入区域没有任何内容时,我应该在屏幕上打印数组内容。
有人能告诉我用户输入同时存储在哪里吗?我可以在哪里学习/研究 C 编译器下底层发生的情况?
最佳答案
声明
fgets(input, sizeof(input), stdin);
是错误的,因为sizeof(input)
会给你指针input
的大小,而不是分配的内存的大小。将其更改为
fgets(input, 20, stdin);
要输出其余字符,请尝试此
char rest;
printf("\nEnter a very long string.\n\n>>");
fgets(input, 20, stdin);
printf("%s\n",input);
while((rest=getchar())!='\n')
{
putchar(rest);
}
Can it not be a solution that I output all the character from input area by
getchar()
. I mean, I would not need array in the beginning anymore?
getchar
是一个输入函数,不能将其用于输出。您可以使用 putchar
来完成此操作。如果您只想输出其余字符,则无需使用数组。我将 charrest[]
更改为 charrest
。
Can anybody tell where the user input is stored meanwhile?
输入存储在系统缓冲区(shell)中。当您按 Enter 或 Return 键时,它将转到 C 标准缓冲区。
关于c - 如何输出比分配的内存长的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20782551/