user276472
user276472

Reputation:

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.

Upvotes: 2

Views: 333

Answers (3)

Kyle Butt
Kyle Butt

Reputation: 9790

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.

Upvotes: 2

slim
slim

Reputation: 2583

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

Upvotes: 1

IVlad
IVlad

Reputation: 43467

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.

Upvotes: 4

Related Questions