[SOLVED] Convert char[] to int

Hi there.

This may sound stupid, but I can't convert a char array to an integer.

What I mean is

• I'm starting with a numeric string, "abcd"
• I can successfully convert to a char array = {'a','b','c','d','\0'}
• Then I want to convert to int = abcd

But the output is 2283... whaaat?

``````void setup()
{
Serial.begin(9600);
String str_size = "4987"; // max 9999
char str_size_char[5]; // additional char for NULL termination
str_size.toCharArray(str_size_char,5);
Serial.print("char: ");
Serial.println(str_size_char);
int str_size_int = int(str_size_char);
Serial.print("int: ");
Serial.println(str_size_int);
}

void loop()
{
delay(1000);
}
``````

Sorry about the question but I'm not making any sense out of this.
footswitch

Not sure how efficient this is as I'm just getting started with embedded system - but there atoi that you can use (I think)

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

footswitch:
Hi there.

• Then I want to convert to int = abcd

An integer is a single number, and in decimal notation cannot be abcd. An integer can be -33 or 99 or 234 but not abcd.

(Unless you are thinking of hexadecimal notation, but I don't think you are somehow.)

@ofransen
abcd represents a numerical character, as forementioned.
So it can be anything from 1 (not 0001) to 9999.

Sorry for the confusion.
When I get home I'll check the post above. Thanks.
footswitch

``````int str_size_int = int(str_size_char);
``````

That's a (an ill-advised) cast, not a conversion.
You could try "atoi".

@AWOL
Thank you for correcting my terminology.
atoi() works perfectly and doesn't need any #include. Thank you so much.
How come this is not documented?
Is it part of the C/C++ language and, as such, considered as not needed to document in the Arduino website?

Cheers,
footswitch

How come this is not documented?

Beats me.
It's one of the commonest topics here.

It is a standard C Library function, and is provided for the Arduino by the AVR LibC library. There is a short, out of the way reference to this library on the Arduino reference page. Many of the library headers are already included as part of the Arduino core sources, but not all of them.

I can only guess that the reason it is not more prominently and extensively documented is that the Arduino team felt it would be too overwhelming for beginners.