2011-09-12 35 views
61

Obtengo un valor int de uno de los pines analógicos en mi Arduino. ¿Cómo puedo concatenar esto a un String y luego convertir el String a un char[]?Conversión de una cadena int o de cadena en una matriz char en Arduino

Se sugirió que intente char msg[] = myString.getChars();, pero recibo un mensaje de que getChars no existe.

+5

¿Realmente necesita una matriz modificable? De lo contrario, podría usar 'const char * msg = myString.c_str();'. A diferencia de 'toCharArray()', 'c_str()' es una operación de copia cero, y la copia cero es algo bueno en dispositivos con memoria limitada. –

Respuesta

99
  1. Para convertir y anexar un número entero, utilice operator += (o función miembro concat):

    String stringOne = "A long integer: "; 
    stringOne += 123456789; 
    
  2. Para obtener la cadena como tipo char[], utilice toCharArray():

    char charBuf[50]; 
    stringOne.toCharArray(charBuf, 50) 
    

En el ejemplo, solo hay espacio para 49 caracteres (suponiendo que termina con nulo). Es posible que desee que el tamaño sea dinámico.

+11

Me ahorró un montón de tiempo de retoque. ¡Gracias! Para hacer dinámico el tamaño char [], haga algo como 'char charBuf [stringOne.length() + 1]' – loeschg

+8

Lo hice dinámicamente así: 'char ssid [ssidString.length()];' 'ssidString.toCharArray (ssid, ssidString.length())' – dumbledad

+1

@loeschg ¡Gracias, lo intenté sin el '+ 1' al principio, pero tu solución funcionó para mí! –

39

Sólo como referencia, aquí es un ejemplo de cómo convertir entre String y char[] con una longitud dinámico -

// Define 
String str = "This is my string"; 

// Length (with one extra character for the null terminator) 
int str_len = str.length() + 1; 

// Prepare the character array (the buffer) 
char char_array[str_len]; 

// Copy it over 
str.toCharArray(char_array, str_len); 

Sí, esto es dolorosamente obtuso para algo tan simple como una conversión de tipos, pero lamentablemente es la forma más fácil.

0

Nada de eso funcionó. Aquí hay una manera mucho más simple ... la etiqueta str es el puntero a lo que ES una matriz ...

String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string 

str = str + '\r' + '\n'; // Add the required carriage return, optional line feed 

byte str_len = str.length(); 

// Get the length of the whole lot .. C will kindly 
// place a null at the end of the string which makes 
// it by default an array[]. 
// The [0] element is the highest digit... so we 
// have a separate place counter for the array... 

byte arrayPointer = 0; 

while (str_len) 
{ 
    // I was outputting the digits to the TX buffer 

    if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty? 
    { 
     UDR0 = str[arrayPointer]; 
     --str_len; 
     ++arrayPointer; 
    } 
} 
+0

'str' no es un puntero a una matriz, es un objeto' String' que implementa el operador '[]'. –

Cuestiones relacionadas