Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am getting an int value from one of the analog pins on my Arduino. How do I concatenate this to a String and then convert the String to a char[]?

It was suggested that I try char msg[] = myString.getChars();, but I am receiving a message that getChars does not exist.

share|improve this question

2 Answers

up vote 17 down vote accepted
  1. To convert and append an integer, use operator += (or member function concat):

    String stringOne = "A long integer: ";
    stringOne += 123456789;
    
  2. To get the string as type char[], use toCharArray():

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

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

share|improve this answer
2  
Saved me a lot of tinkering time. Thanks! In order to make the char[] size dynamic, do something like char charBuf[stringOne.length()+1] – loeschg Mar 23 '12 at 19:37
I did it dynamically like this: char ssid[ssidString.length()]; ssidString.toCharArray(ssid, ssidString.length()); – dumbledad Dec 14 '12 at 13:45

Unfortunately, I can't test at the moment, but one option would be to split your prints. For example,

Serial.print("analogValue:\t");
Serial.print(analogRead(0));
Serial.print("\n");

Or you should be able to use std functions, like itoa() (int to ASCII) or others.

Serial.println("analog value: " + itoa(analogRead(0)));

(You might need includes at the top of your code for itoa (

#include <stdio.h>
#include <stdlib.h>

))

share|improve this answer
1  
I am not trying to do a Serial Print, I am trying to concatenate a Char variable and a String into one long Char variable. – Chris Sep 12 '11 at 15:01
1  
-1 I can't see how this is an answer – dumbledad Dec 14 '12 at 13:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.