简体   繁体   中英

Unnecessary newlines using function 'printf'

When allocating Strings on the heap (with 'malloc'),
and initializing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM