lundi 29 novembre 2021

Unexpected behavior concatenating string

I am trying to concatenate two strings in C++11 and I am often getting an unexpected behavior.

First, I have a function that converts any type to string :

template <class T>
static inline const char * toStr(T arg) {
    stringstream ss;
    ss << arg;
    return (ss.str()).c_str();
}

Then, I use this function like this :

string measure_name;
for (unsigned long j = 0; j < 1280; j++) {
    measure_name = string("ADC_") + toStr(j);
    cout << measure_name << endl;
}

Everything goes well untill I reach a 4 digit number (> 999) : my variable measure_name often equals to "ADC_ADC_"... and it happens randomly. I did some research and found nothing about this strange behavior.

For your information, this issue is fixed if toStr returns a string and not a const char *.

Also, if I try to print the returned value, I never see it equal to "ADC_ADC_", so I believe the real issue comes from the concatenating instruction :

string measure_name;
for (unsigned long j = 0; j < 1280; j++) {
    const char* tmp = toStr(j);
    if (!strcmp(toStr(j), "ADC_ADC_"))
        cout << "bug" << endl; //never happens
    measure_name = string("ADC_") + tmp; //problem comes from here
    cout << measure_name << endl;
}

I just wanted to understand what I am doing wrong there... I know I am using very old C++ but it should work anyway.

Thank's for your help.

Aucun commentaire:

Enregistrer un commentaire