Concatenate variables in C ++

4

I have a method that should return char* but I can not concatenate the variables:

char* format(char* model){
    char* format;
    format+=day+"";
    return format;
}

The variable day is type int , I come from java so I still can not do this procedure.

For now model does not do anything because I can not even print format .

    
asked by Felipe Chaparro 31.08.2018 в 04:41
source

1 answer

3

If your goal is to concatenate variables, use a std::stringstream :

std::stringstream ss;

// Concatenar variable en un texto:
int variable = 0;
ss << "Texto " << variable;

// Mostrar resultado por consola
std::cout << ss.str() << '\n';

If your goal is "method that should return char* " I'll tell you never to do a method like this:

  • In C ++ it is better to manage character strings with std::string , not with character pointers.
  • If you manage a character string with pointers to character, you will have to go through all the tedium of managing the memory manually.
  • 1
    std::string concatena(const std::string &texto, int valor) {
        return texto + std::to_string(valor);
    }
    
    2
    char* concatena(const std::string &texto, int valor) {
        auto v = std::to_string(valor);
        char *resultado = new char[v.length() + texto.length() + 1];
        auto p = std::copy(texto.begin(), texto.end(), resultado);
        *p = ' ';
        ++p;
        std::copy(v.begin(), v.end(), p);
        return p;
    }
    
    // Si usamos 'concatenar' debemos borrar la memoria manualmente:
    auto v = concatenar("Texto ", 0);
    // ... usar v ...
    delete[] v;
    
        
    answered by 31.08.2018 / 08:58
    source