[英]why I can't get multiple spaces in *?
int main()
{
int input;
printf("input lenth : \n");
scanf("%d", &input);
while(getchar()!='\n')
continue;
printf("input str : \n");
char* sentence = (char*)malloc(sizeof(char) * input);
fgets(sentence, sizeof(sentence), stdin);
reverse(sentence, strlen(sentence));
free(sentence);
return 0;
}
I learn fgets
can get space.我学习fgets
可以获得空间。
so I malloc
enough space to sentence
ex) 100所以我malloc
有足够的空间来sentence
ex) 100
and I input I am a boy
我输入I am a boy
But when I print my sentence
, IT just print I am a
...但是当我打印我的sentence
时,它只是打印I am a
...
what's th problem?有什么问题?
This statement这个说法
fgets(sentence, sizeof(sentence), stdin);
is incorrect.是不正确的。 It seems you mean看来你的意思
fgets(sentence, input, stdin);
Otherwise sizeof( sentence )
will yield the size of a pointer declared like否则sizeof( sentence )
将产生声明为的指针的大小
char* sentence = (char*)malloc(sizeof(char) * input);
Pay attention to that the function fgets
can append the new line character '\n'
to the entered string.注意 function fgets
可以 append 换行符'\n'
到输入的字符串。 You should remove it like你应该像这样删除它
sentence[ strcspn( sentence, "\n" ) ] = '\0';
When you say:当你说:
fgets(sentence, sizeof(sentence), stdin);
It gives you size of pointer char ie 8 (Depends on 32 & 64 system you use).它为您提供指针字符的大小,即 8(取决于您使用的 32 和 64 系统)。 So you are able to receive 7 characters only as fgets assignes '\0' character to last character.因此,您只能在 fgets 将 '\0' 字符分配给最后一个字符时接收 7 个字符。
So, use length you received from the user ie 100.因此,使用您从用户那里收到的长度,即 100。
fgets(sentence, input, stdin);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.