I'm new to C and am having trouble with strings. What I would like to do is create a string like "val1, val2, val3" in a loop.
Currently my code looks something like:
char tagstr[60] = "";
int k;
int n = 5;
for (k=0; k < n; k++) {
char temp[10] = "";
sprintf(temp, ", val%d", k);
strcat(tagstr, temp);
}
But the output of tagstr is ", val#", where # is some long integer value. I'm guessing I'm doing something wrong with pointers here but I've tried everything I can think of without success... any help would be much appreciated.
EDIT: more context, if it helps:
int tagsClosed = strlen(pch1) - strcspn(pch1, ")");
do {
if (curTag.size > 0) {
// problem section
char tagstr[60] = "";
int k;
for (k = 0; k < 5; k++) {
char temp[10] = "";
sprintf(temp, ", val%i", temp, k);
strcat(tagstr, temp);
}
// This prints out something like ", val-890132840" x 5 (same number)
printf ("String is now: %s\n", tagstr);
}
curTag = *(curTag.parent);
tagsClosed--;
} while (tagsClosed > 0);
curTag is a struct:
typedef struct Tag {
char * name;
int size; // number of children
int tagnum;
struct Tag* parent;
} Tag;
temp[5]isn't bug enough to hold ", valk" make it temp[10] or something just to be sure you have enough space.