-1

I have the following:

char rank[100][100];
int score = 5;

strcpy(rank[0], "%d" score);

However, strcpy() does not accept these arguments. Is there any way to append a formatted string into my array?

yezi3
  • 1
  • 1
  • 3
  • 3
    You want [`snprintf`](http://en.cppreference.com/w/c/io/snprintf). – Kninnug Sep 20 '15 at 15:58
  • is that appending or copying? have similar doubts on sprintf family, unless handled very carefully will provide very unusual results – asio_guy Sep 20 '15 at 16:16
  • strcpy() does NOT evaluate format specifiers. A read of the man page for strcpy() will fill you in on the details. sprintf() does evaluate format specifiers. suggest replace `strcpy` with `sprintf` with appropriate parameters – user3629249 Sep 21 '15 at 20:55

2 Answers2

3

You could use sprintf:

char rank[100][100];
int score;

sprintf(rank[0], "%d", score);

Note however that snprintf is the buffer overflow-safe alternative.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • 1
    Better use `int w = snprintf(rank[0], sizeof(rank[0]), "%d", score);` then test that `w` is less than `sizeof(rank[0])` -practically that would *always* be the case – Basile Starynkevitch Sep 20 '15 at 16:01
1

There is no direct way to do this with strcpy().

However, you can make use of snprintf() first to prepare your string and the use the same as the second argument of strcpy().

FWIW, in this case, you can directly use snprintf() on rank[n], also.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261