2

In my project I need to convert a string to a char array. From various examples I concluded thattoCharArray() will convert a string to a char array. But I failed to do so. The error is:

'a' does not name a type

The code I am using is:

String a = "45317";char b[6];a.toCharArray(b,6);

Resources arehttps://www.arduino.cc/en/Reference/StringToCharArray andhttp://forum.arduino.cc/index.php?topic=199362.0

dda's user avatar
dda
1,5951 gold badge12 silver badges18 bronze badges
askedMar 20, 2017 at 17:24
Tanmay Yerunkar's user avatar
1

2 Answers2

4

If you're trying to use a method ofa in the global scope, that's doomed to failure. You can only call methods within functions.

If all you want is a char array with "45317" in it then just use:

char *b = "45317";

If you want to convert a string that is built at runtime into a char array, then your current method is correct - you just have to do it in the right place.

answeredMar 20, 2017 at 17:26
Majenko's user avatar
0
5

There's a built in conversion which will return the underlying string-contents as a NULL terminated character array:

 String foo = "Steve was here" char *text = foo.c_str();

That is probably all you need, unless you do want to copy into a buffer. In that case you can use the standard C library to do that:

 // Declare a buffer char buf[100]; // Copy this string into it String foo = "This is my string" snprintf( buf, sizeof(buf)-1, "%s", foo.c_str() ); // Ensure we're terminated buf[sizeof(buf)] = '\0';

(You might preferstrcpy,memcpy, etc tosnprintf.)

answeredMar 20, 2017 at 17:31
1
  • 1
    1)c_str() is no replacement fortoCharArray(): your first example fails to compile with “error: invalid conversion from ‘const char*’ to ‘char*’”. Of course, if you only need aconst char *, thenc_str() is to be preferred. 2) In terms of code size,snprintf() is a very inefficient way of copying a string. 3) No need to subtract one fromsizeof(buf) in the second argument tosnprintf().CommentedMar 20, 2017 at 18:46

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.