Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 609
Gary M Avatar asked Apr 02 '14 08:04

Gary M


3 Answers

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.

like image 58
unwind Avatar answered Sep 28 '22 02:09

unwind


you can use a single statement for this,

snprintf(filename,sizeof(filename),"./speeches/speech%d.txt",a);
like image 40
LearningC Avatar answered Sep 28 '22 01:09

LearningC


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");
like image 28
vasanth89 Avatar answered Sep 28 '22 00:09

vasanth89