-5

I have a char array that has '4''5'. But I want to convert those characters into actual integers so I subtract '0' from each index of the char array and store it into the same array. If I want to set an int called value to the 45 (the stuff inside the char array) How would I do it?

  • Could you please give an example input and an example output ? – Ely Jun 27 '15 at 20:01
  • 1
    There are plenty of existing questions about parsing numbers out of strings. Have you read any of them? – Lightness Races in Orbit Jun 27 '15 at 20:01
  • `int i; sscanf(charArray, "%d", &i);` `atoi(charArray))` – mazhar islam Jun 27 '15 at 20:03
  • a) `scanf`, b) `atoi`, c) for positive integers in `int` range eg. `int sum = 0; for(int i = 0; i < strLen; i++) { sum *= 10; sum += chararr[i] - '0' }` –  Jun 27 '15 at 20:04
  • possible duplicate of [Convert char array to a int number in C](http://stackoverflow.com/questions/10204471/convert-char-array-to-a-int-number-in-c) –  Jun 27 '15 at 20:05
  • Yeah same question. sorry and thanks! – Sandra Delatorre Jun 27 '15 at 20:10
  • If you end up choosing `atoi`, think again. If you get 0 back, you can't tell whether the conversion was successful. In C, `strtol` is a good replacement and in C++, `stoi` uses almost the same interface as `atoi`. – chris Jun 27 '15 at 20:11
  • http://stackoverflow.com/questions/6093414/convert-char-array-to-single-int & http://stackoverflow.com/questions/4633252/how-to-cast-an-array-of-char-into-a-single-integer-number – marc_s Jun 27 '15 at 20:33

2 Answers2

0

atoi() converts string to integer. For example if you already have the char array and integer variable declared you can do:

   val = atoi(theCharArray);

Duplicate question

Community
  • 1
  • 1
0
int int_value;
int_value = atoi(your_char_array);

the atoi() Function is used to convert string to int.
more information about atoi() Here.

marc_s
  • 455
  • 1
  • 4
  • 15