Jack_of_all
Jack_of_all

Reputation: 23

Changing char* string in a C loop

I am trying to change a string within a loop to be able to save my images with a changing variable. Code snippet is as follows:

for (frames=1; frames<=10; frames++)
{
    char* Filename = "NEWIMAGE";
    int Save_Img = is_SaveImageMemEx (hCam, Filename, pMem, memID, 
    IS_IMG_PNG, 100);
    printf("Status Save %d\n",Save_Img);
}

What I want to do is put a variable that changes with the loop counter inside Filename so my saved file changes name with every iteration.

Any help would be great.

Upvotes: 2

Views: 159

Answers (2)

Jens
Jens

Reputation: 72727

Create a file name string with sprintf and use the %d format conversion specifier for an int:

char filename[32];
sprintf(filename, "NEWIMAGE-%d", frames);

sprintf works just like printf, but "prints" to a string instead of stdout.

If you declared frames as an unsigned int, use %u. If it is a size_t use %zu. For details see your friendly printf manual page, which will tell you how you can for example zero pad the number.

Be sure that the character array you write to is large enough to hold the longest output plus an extra '\0' character. In your particular case NEWIMAGE-10 + 1 means 11 + 1 = 12 characters is enough, but 32 is future-proof for some time.

If you want to program like a pro, look at the snprintf and asnprintf functions, which can limit or allocate the memory written to, respectively.

Upvotes: 6

dbush
dbush

Reputation: 224677

You can use sprintf to create a formatting string:

char Filename[50];
sprintf(Filename, "NEWIMAGE%d", frames);

Upvotes: 3

Related Questions