String to int ?

Hello

sorry if the question seems stupid, please just consider I'm a beginner (and i'm affraid I'll aways be)

I did not find any way to transform a String containing only one char (like "3") into an "int" (like 3)
(or more "123" into 123)

In other words, is there a better way that doing this ?

  • String c = "";*
  • int pgmMode = 0;*
    (…)
  • if(c=="1"){*
  • pgmMode = 1;*
  • }*
  • else if (c=="2") {*
  • pgmMode = 2;*
  • }*
    (…)
  • else {*
  • pgmMode = 0;*
  • }*

Thank's for your answers.

The String class has a toInt() method.

So obvious… How could i miss that!
(as I said i'll always be a begginer !)
THANK's.

use below link.
http://www.programmingsimplified.com/c/source-code/c-program-convert-string-to-integer-without-using-atoi-function

If you're only converting digit characters and don't want to use the String class, you can use:

char digit = '3';
int number = digit - 48;
char array[] = "01234";
number = array[3] - 48;

The ASCII value for the character 3 is 51. So in either case, number factors to: number = 51 - 48 = 3, which is an int value.

Various methods I've seen.

    int n;
    char carray[6]; //converting string to number
    readString.toCharArray(carray, sizeof(carray));
    n = atoi(carray); 


    char carray[readString.length() + 1]; //determine size of the array
    readString.toCharArray(carray, sizeof(carray)); //put readString into an array
    int n = atoi(carray); //convert the array into an Integer 
 

    int n = readString.toInt();