开发者

Unnecessary newlines using function 'printf'

When allocating Strings on the heap (with 'malloc'),

and i开发者_如何学运维nitializing them with the standard input (using 'fgets),

an unnecessary newline appears between them when trying to print them (with 'printf' and %s formatting).

for example:

main()
{
    char *heap1;
    char *heap2;

    heap1=malloc(10);
    heap2=malloc(10);
    fgets(heap1,10,stdin);
    fgets(heap2,10,stdin);
    printf("%s%s",heap1,heap2);
}

with input "hi1\nhi2" produces "hi1\nhi2". compiled using gcc 4.3.4 for Debian.


fgets also reads the '\n' (newline) character. You should remove it if you don't want it to print like that.

heap1[strlen(heap1) - 1] = '\0';

after you read the contents of heap1.


fgets returns the newline as part of the string.

See man 3 fgets. Specifically:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.


fgets is probably appending the newline. Try trimming the string you get back from fgets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜