View Full Version : Help in Arduino char/string

08-27-2013, 02:16 AM
hi sir/ma'am how to convert a char to a string?

i got this error.

sketch_aug27a:90: error: invalid conversion from 'char' to 'const char*'
sketch_aug27a:90: error: initializing argument 1 of 'String::String(const char*)'
sketch_aug27a:93: error: invalid conversion from 'char' to 'const char*'
sketch_aug27a:93: error: initializing argument 1 of 'unsigned char String::equals(const char*) const'

char x;

if ((x,n)>0 // number, number length
String num=x;


08-27-2013, 01:56 PM
If you read the error message: Your real problem is that you're trying to convert a number to a string. It complains it can't initialize the string "num" from the char variable "x". This can be done, but it's pretty inefficient (look into sprintf(), and perhaps the Arduino library also has itoa().)

The range of a char is 0 through 255, so trying to compare the converted string to "12345" will always fail, by the way. And it's much more efficient to compare integers directly than going through strings.

Also, the if statement makes no sense. First, it won't even compile the way you pasted it -- there needs to be a second closing parentheses before the comment.
Second, the (x,n) statement doesn't do what you think it does. It will use the comma operator to evaluate "n," which evaluates to some memory address, which when taken as an integer is greater than 0, which means that the if() will always be true (with a compiler warning for the treating-address-as-integer part.)

08-30-2013, 10:09 AM
hi sir/ma'am how to convert a char to a string?

Like this...

char s[10];
char t;

s[0] = t; // s[0] is type char; 0th position in array gets value of t
s[1] = '\0'; // null terminate

The char type holds a single byte value. Usually used for reading/writing single characters. The above converst to a string, although I'm pretty sure there's no such thing as a string, per-se, in C/C++, just an array of char or pointer to char. Converting to a C++ String object is another story.

The syntax for declaring and initializing an object in C++ is:

String num("Hello world");

It's expecting a const char *, the "Hello world" constant.

For the rest of your code...


You're missing a type. Is it a char?

if ((x,n)>0 // number, number length

I have to say I've never seen this syntax before but I guess it is a C++-ism. IIWY I'd just go old school

if (x > 0 && n > 0)

String num=x;

Even if you somehow initialize num to contain x, it'll never equal "12345". Are you trying to convert an int to a string? Look at the atoi function as mentioned in the previous post.

What's the bigger picture? What are you trying to accomplish?

hope this helps,