2

I would like to append the integer n to the string a, resulting in "asd 2". For some reason I cannot figure out how to do it, I have tried casting int to char and using strcat(), I tried it with sprintf() yet none of it works.

char* a = "asd ";
int n = 2;

Surely there has to be a simple way to do this? I would appreciate any help

elfz
  • 21
  • 1
  • 5
    Show your attempt with `sprintf` because that should work. – Cheatah Apr 09 '22 at 23:50
  • I put `sprintf( a, "%d", b);` and printing `a` just resulted in the output `2` – elfz Apr 09 '22 at 23:55
  • If you're using `sprintf`, take especial care that you're remembering to _allocate space for the new string_ (the `buffer` parameter). You can't, for instance, write to an uninitialized `char*` or a `char*` that references a string literal. – Brian61354270 Apr 09 '22 at 23:55
  • 1
    @elfz Trying to write to `a` when `a` points to a string literal is undefined behavior. See [Why do I get a segmentation fault when writing to a `char *s` initialized with a string literal, but not `char s[]`?](https://stackoverflow.com/q/164194/11082165) – Brian61354270 Apr 09 '22 at 23:58
  • Also note that `sprintf(buf, "%s some further text", buf);` is [undefined behaviour](https://en.cppreference.com/w/c/language/behavior) as well. See the NOTES section of: [`man 3 sprintf`](https://man7.org/linux/man-pages/man3/printf.3.html#NOTES) – Oka Apr 10 '22 at 00:29

1 Answers1

2

sprintf solution

char result[100];
char* a = "asd";
int n = 2;
sprintf(result, "%s %d", a, n);
pm100
  • 48,078
  • 23
  • 82
  • 145
  • Thank you so much! If I wanted to repeatedly add integers onto the string does that mean that before I add anything new I'd have to create a new result[] array? – elfz Apr 10 '22 at 00:44
  • @elfz sprintf does not append (thats why you went wrong before), you should `sprintf` the new number into a new buffer then `strcat` it to the end of 'result'. Make SURE you have enough space in result, you can use `strncat` to make sure you dont overrun resukt – pm100 Apr 10 '22 at 00:49
  • @elfz you can append with an extra pointer (e.g.): `char *res = result; res += sprintf(res, "hello"); res += sprintf(res, " world");` – Craig Estey Apr 10 '22 at 01:54