sprintf write to string with \n

24,823

Solution 1

Looks like its working for me. I put brackets [] around the string to prove it.

Have a look here: http://ideone.com/3rbwF

Solution 2

If you are on a Windows computer you might need \r\n instead of just the newline. The library should handle it though.

Solution 3

Allocate enough space for string

#include <stdio.h>
#include <stdarg.h>

main() {
    char string[7];
    char str1[] = "a";
    char str2[] = "b";
    sprintf(string, "0 %s %s\n", str1, str2);
    printf("%s", string);
}
Share:
24,823
brunoais
Author by

brunoais

Updated on November 18, 2020

Comments

  • brunoais
    brunoais over 3 years

    I have this code:

    str1= "a";
    str2= "b";
    sprintf(string, "0 %s %s\n", str1, str2);
    

    string then contains:

    "0 a b"

    instead of (what I want):

    "0 a b
    "

    How can I solve that?

    Note: I place the quoting of the var string inside " so that you could understand the situation.

    Edit:

    Problem solved I added 1 to the size and it worked. I don't completely understand why but it's solved

  • brunoais
    brunoais over 12 years
    Doesn't work. The \n is not inside the string. And I used printf to test it.
  • brunoais
    brunoais over 12 years
    it's in linux, though. (I'll add it to the tags)
  • brunoais
    brunoais over 12 years
    In that case, it would be: char string[8]; and not what you show. In what you show the space for \0 is not alloced
  • nos
    nos over 12 years
    @brunoais yes it is. "0 a b\n" takes up 7 chars. (the newline is escaped in the source code, in the compiled code it takes up just 1 char)
  • brunoais
    brunoais over 12 years
    Ups, I miscounted the number of chars. he's right.