C ++: dando valor a la matriz de caracteres

Entonces tengo esto:

char uloginName[] = "derp";
char mew[33] = "home/home/" << uloginName << "\0";

I am trying concatinate uloginName with the rest of the string that will later be converted to an array of char. But it keeps returning me an error. I don't know how to do it. Also, I must use only char[] type as of this moment; No string.

Gracias por la ayuda.

preguntado el 01 de febrero de 12 a las 01:02

"\0" y "" are equivalent; you should null-terminate with mew[upper_bound] = '\0'. -

You have several answers that tell you to use strcat/strncat, and they are correct. But they don't explain why what you're doing generates an error. You mistook the integral type "char" for a class that defines the << operator (like cout). But the char data type is not a class. It's an integral type that doesn't understand the << operator. -

Thanks @CareyGregory, that truly helps. -

3 Respuestas

char uloginName[]="derp";
char mew[33]="home/home/";
strcat(mew, uloginName);

Puede usar el strcat on arrays of characters, so long as there is sufficient space and they are terminated with a zero byte.

Respondido 01 Feb 12, 05:02

So should I say char uloginName[]="derp\0"; ¿en lugar de? - Ren

That's redundant. When you write "derp", you've already specified a C-style string with a zero terminator. If you print sizeof(uloginName), you'll see it's 5 already. You could also do {'d','e','r','p','\0'} si tu quieres. - David Schwartz

Thank you, also, I think strcat() is for strings only. I am working with char type right now for which I am using strncat(). Corrígeme si estoy equivocado. - Ren

Your character arrays contain C-style strings. A "string" just means that it's terminated by a zero byte. Unless you separately track the lengths, you'll have to use the fact that their strings too -- otherwise how will you know how many bytes to work with? - David Schwartz

Utilizan strncat ().

Respondido 01 Feb 12, 05:02

Parece que estás buscando std::ostringstream, which is a versatile and far less error-prone way of handling strings in C++. strcat(), strncat and their kin are hangovers from C and should be used cautiously in C++.

char uloginName[] = "derp";
std::ostringstream mew;
mew << "home/home/" << uloginName;

Respondido 03 Feb 12, 13:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.