toInt() how do i convert char to int

I have a very basic question that is doing my head in. I have keypad (0-9 plus * #).

The library return me a char which equals the pressed button which works perfectly well.

I need to be able to convert the char into a int so that I can assign an array variable according to the pressed number.

eg: array[pressed button number here]

This should be simple with toInt() function from my understanding but I cannot get it working. Here is some simple code that also doesn't work. Can anyone advise why?

int x; //this needs to be the integer value of str

char str;

void setup() {


void loop() {

str = "7"; //assign a number to the string variable

x = str.toInt();


I receive this error on compiling:

exit status 1

request for member 'toInt' in 'str', which is of non-class type 'char'

the function toInt() is a String function. It can't be used with char data type.

A char uses single quotes ('7'). "7" as a string has to be declared a string (char str[] = "7";

Use the function atoi() with C-strings:

char c_string[]="123";
int value = atoi(c_string);

Hi @richo777
try this way;

byte x; // 
int abc[10];
char str;

void setup () {

void loop () {

  str = '7'; 

  x = str & 0x0F;
  abc[x] = 45;

There are different ways that data can be represented and each way has functions to handle the data. Here are ways to change a character ('0' - '9') to a number (0 - 9) and a string ("7") to a number (7).

int x; //this needs to be the integer value of str

char chr = '4';  // declare a char
char str[] = "7";  // declare one character string (+ 1 for the null terminator (2 bytes total))

void setup()

   x = chr - '0';  // to get the number (0-9) from a character subtract '0' or 48 (dec) or 0x30 (hex)
   Serial.print("char chr converted to a number = ");

   Serial.print("string str converted to a number = ");

void loop()

The atoi() function.

Thank you for the help. I was trying to use string and could not make this work until I realised (super Noob) that the declaration should be String not string and i had my case wrong.
Once I did that then I was able to convert using toInt()
Thanks again.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.