c 删除新行字符帮助
我对 c 很陌生,如果这是一个愚蠢的问题,我很抱歉!
我有这个:
fgets(question,200,stdin);
char *memq = malloc(sizeof(strlen(question)));
memq= question;
但是问题变量的末尾总是有一个新行! 我该如何删除它/防止它发生?
我试过了:
fgets(question,200,stdin);
char *memq = malloc(sizeof(strlen(question))-sizeof(char));
memq= question;
没有效果!
Im fairly new to c sorry if this is a stupid question!
i have this:
fgets(question,200,stdin);
char *memq = malloc(sizeof(strlen(question)));
memq= question;
however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?
i have tried this:
fgets(question,200,stdin);
char *memq = malloc(sizeof(strlen(question))-sizeof(char));
memq= question;
there was no effect!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要摆脱换行符,在 malloc 之前,执行 :
另一种选择(在下面的评论中建议)将执行以下操作:
将 malloc 行更改为:
将分配行更改
为:
to get rid of the newline, before your malloc, do :
an alternative (suggested in the comments below) would be to do the following instead:
change the malloc line to:
change the assignation line:
to:
这段代码被严重破坏了。
如果您打算将数据复制到
memq
中,则需要在其中分配strlen+1
字节(为什么要执行sizeof
?这将分配 4 个字节)字节,因为sizeof(strlen())
是sizeof(int)
)。您不能只是将
question
分配给memq
并期望将数据复制进去。这一切都会覆盖您刚刚malloc
编入的指针memq
,泄漏它。你必须这样做这就是为什么你需要在memq中额外的字节,因为这包括一个空终止符。此时,您可以从
memq
中删除换行符,如其他地方所述。This code is badly broken.
You need to allocate
strlen+1
bytes intomemq
if you plan to copy the data there (why are you doingsizeof
? that will allocate 4 bytes sincesizeof(strlen())
issizeof(int)
).You cannot just assign
question
tomemq
and expect the data to be copied in. All this does is overwrite the pointer you justmalloc
-ed intomemq
, leaking it. You have to doThat's why you need the extra byte in
memq
, since this includes a null terminator. At this point you are in position to remove the newline frommemq
as noted elsewhere.假设您的输入是 ABCDEn,其中 n 代表新行。
您将读取 ABCDEn0,其中 0 代表 null,它终止字符串。
因此,通过去掉最后一个字符,您将去掉空值,而不是换行符。我会像你一样去掉最后一个字符,但然后将(新的)最后一个字符设置为 null 以终止你的字符串。
Let's say your input is ABCDEn where the n represents the new line.
You're going to be reading in ABCDEn0 where 0 represents null, which terminates the string.
So, by taking off the last char, you're taking off the null, not the newline. I would take off the last char as you are, but then set the (new) last char to null to terminate your string.
在这两种情况下,
memq = Question
都是错误。您刚刚丢失了指向新分配的空间的指针,而是将question
的第一个字符的地址复制到memq
使用
strcpy
或者用memcpy
来代替,将question
指向的字符串的内容复制到memq< 指向的内存内容/代码>。
In both cases,
memq = question
is wrong. You've just lost your pointer to new newly-allocated space, and instead copied the address of the first character ofquestion
tomemq
Use
strcpy
ormemcpy
instead, to copy the contents of the string pointed to byquestion
to the contents of the memory pointed to bymemq
.暗示:
删除最后一个字符! (提示提示:你知道长度)
Hint:
Remove the last character! (Hint to hint: you know the length)