String manipulation in C is not something I'm used to, coming from higher level languages. In this situation, I want to be able to make a string of the form fooN
where N is a variable representing a number. In Java, it would look something like
for (int N = 0; N < 5; n++) {
System.out.println("foo"+N);
}
which will output
foo0
foo1
foo2
foo3
foo4
However, I don't know a straighforward way to do that in C. I could probably hack something out where I make a char[] and figure out how to fill it up, but what I have in mind doesn't seem elegant. Is there a simple way that the C language allows concatenating strings and int variables?
Thanks
Is there a simple way that the C language allows concatenating strings and int variables?
Yes, use s*printf()
. The trick is memory management.
Use a fixed sized buffer.
// Coarse calculation of maximum memory needed to string-ify an int
#define INT_STRING_MAX (sizeof(int)*CHAR_BIT/3 + 3)
#define FOO_SZ (3 + INT_STRING_MAX)
char buf[FOO_SZ];
sprintf(buf, "foo%d", n);
println(buf);
Allocate memory. Could use snprintf(NULL, 0, ...
to calculate memory needs.
int sz = snprintf(NULL, 0, "foo%d", n);
char *buf = malloc(sz + 1);
if (buf) {
sprintf(buf, "foo%d", n);
println(buf);
free(buf);
}
Estimate and check memory needs with snprintf()
.
// Assume 64-bit or narrower int and so needs at most 21 bytes
#define FOO_SZ (3 + 21)
char buf[FOO_SZ];
int cnt = snprintf(buf, sizeof buf, "foo%d", n);
if (cnt >= 0 && (unsigned) cnt < sizeof buf) {
println(buf);
} else {
// wrong estimate
}
The best choice depends on how simple, efficient & portable you want.