Question

I'm trying to open different files by having a for loop increment a counter, then appending that counter to the filename to be opened, but I'm stuck on how to use strcat to do this. If I understand right, strcat takes 2 strings, but my counter is an int. How can I make it so that it becomes a string?

for(a = 1; a < 58; a++) {
    FILE* inFile;
    int i;

    char filename[81];

    strcpy(filename, "./speeches/speech");
    strcat(filename, a);
    strcat(filename, ".txt");

Definitely doesn't work since a is an int. When I try casting it to char, because a starts at 1 and goes to 57, I get all the wrong values since a char at 1 is not actually the number 1.. I'm stuck.

Was it helpful?

Solution

You can't cast an integer into a string, that's just not possible in C.

You need to use an explicit formatting function to construct the string from the integer. My favorite is snprintf().

Once you realize that, you can just as well format the entire filename in a single call, and do away with the need to use strcat() (which is rather bad, performance-wise) at all:

snprintf(filename, sizeof filename, "./speeches/speech%d", a);

will create a string in filename constructed from appending the decimal representation of the integer a to the string. Just as with printf(), the %d in the formatting string tells snprintf() where the number is to be inserted. You can use e.g. %03d to get zero-padded three-digits formatting, and so on. It's very powerful.

OTHER TIPS

you can use a single statement for this,

snprintf(filename,sizeof(filename),"./speeches/speech%d.txt",a);

You are right about the strcat function. It only works with strings.

You could use the 'sprintf' function. A modification to your code below:

char append[2]; //New variable
for(a = 1; a < 58; a++) {
  FILE* inFile;
  int i;

  char filename[81];

  strcpy(filename, "./speeches/speech");
  sprintf(append,"%d",a); // put the int into a string
  strcat(filename, append); // modified to append string
  strcat(filename, ".txt");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top