How to place an integer at the end of a string?

Asked

Viewed 321 times

0

I need to loop up n placing an integer at the end of a string.

Ex: string "E0" and an integer of 0 to n, getting something like this:

E00, E02, E03, ... , E0n

char ent[3] = {'E','0'};
char a[1];
int n=5;//exemplo

for (int i = 0; i < n; i++) {
        itoa(i,a,10);
       strcat(ent,a);
            printf("novo ent: %s \n ",ent);
        }

I do not understand what is wrong, because it is printing only the variable "a" and not "ent+a".

2 answers

1

The first problem that causes the code to fail is that it is not allocating space to the terminator in the string that passes to itoa. Remember that the result is a correctly completed string so it will have at least two characters, what you have put and the terminator.

That’s why char a[1] it has to be at least char a[2]. The very one itoa is not something you should use because it is not standard and so it is not available on all compilers, as in mine. You should instead use sprintf that is easy in the same and is standard.

The other problem is that each concatenation is permanent over the string ent. That’s why your texts are growing: E00, E001, E0012, etc. With each iteration of the for has to start in the original string, which can duplicate the original with strdup before using.

Fixing these two problems and keeping the itoa would look like this:

int main() {
    char ent[3] = {'E','0'};
    char a[2];
    int n=5;//exemplo

    for (int i = 0; i < n; i++) {
        itoa(i,a,10);
        char *ent_dup = strdup(ent); //criar duplicado
        strcat(ent_dup,a); //usar duplicado até ao fim
        printf("novo ent: %s \n ",ent_dup);
        free(ent_dup); //liberar duplicado
    }
    return 0;
}

Note that you have to release the string returned by strdup through free if you want to avoid memory leaks.

Using sprintf would look like this:

int main() {
    char ent[3] = {'E','0'};
    char saida[10];
    int n=5;

    for (int i = 0; i < n; i++) {
        sprintf(saida, "%s%01d", ent, i);
        printf("novo ent: %s \n ",saida);
    }
    return 0;
}

See this latest version on Ideone

  • I think with your use of sprintf is unnecessary to concatenate with strcat

  • @Jeffersonquesado Yes it is indeed. I just switched the sprintf for itoa and I didn’t even remember I could do everything with just the sprintf. Thank you for the comment.

  • for nothing. I put a supplementary answer that made more sense before its edition. I think now it would be better to merge my answer in yours, which you think?

  • @I don’t think so. Looks good just as it is as a complement, and with a variant of using ascii straight to when number has only one digit.

1


Just to give more possibilities to the solutions presented by @Isac.

Alternative use of sprintf

int main() {
    char prefixo[3] = {'E','0'};
    char ent[4];//se quiser números com 2 casas decimais, basta por tamanho 5
    int n=5;//exemplo

    for (int i = 0; i < n; i++) {
        sprintf(ent, "%s%d", prefixo, i); //sprintf em vez de itoa
        printf("novo ent: %s \n ",ent);
    }
    return 0;
}

Direct character writing

You can simply compute the desired character and place it at position 2 of the string :

int main() {
    char ent[3] = {'E','0', '\0', '\0'};
    char num;
    int n=5;//exemplo

    for (int i = 0; i < n; i++) {
        num = '0' + i; // calculando o caracter a partir de um offset i do caracter '0'
        ent[2] = num;
        printf("novo ent: %s \n ",ent);
    }
    return 0;
}

this solution was drawn to one-digit numbers, you can do it better

Browser other questions tagged

You are not signed in. Login or sign up in order to post.