简体   繁体   中英

Convert integer to be used in strcat

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.

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 eg %03d to get zero-padded three-digits formatting, and so on. It's very powerful.

你可以用一个语句,

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM