-2

My code is this:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
   int a;
   cout << "Enter a number" << endl;
   cin >> a;
   string a_str;
   ostringstream temp;
   temp << a;
   a_str = temp.str();

   for(int i = 0; i < a_str.length(); i++) {
      char c = a_str[i]; //How this character convert to integer number
   }

   system("pause");
   return EXIT_SUCCESS;
}

How char c convert to int ? I need this for I need this because I need to get the highest digit

fvu
  • 32,488
  • 6
  • 61
  • 79
Leon
  • 43
  • 1
  • 6
  • You mean that you have e.g. the character `'1'` and you want the integer `1`? Check an [ASCII table](http://www.asciitable.com/) and you might figure it out. Hint: It involves subtraction. – Some programmer dude Jan 30 '14 at 12:41
  • Char is in fact a kind of int (int8 or int16); so you can do the conversion like "int v = a_str[i] - '0';" – Dmitry Bychenko Jan 30 '14 at 12:44

5 Answers5

1

If you want to get char '8' to int 8 for example, this would be enough for ascii

int i = a_str[0] - '0';
deeiip
  • 3,319
  • 2
  • 22
  • 33
1
const int i = atoi(&c); 

should work too

beardedN5rd
  • 185
  • 6
0

char is already an integral type. I think you meant the following

char c = a_str[i] - '0';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0
atoi(c) for integers
atof(c) for floats 

do the trick

madduci
  • 2,635
  • 1
  • 32
  • 51
0

You can also write it yourself: This works for normal keys (not arrows keys or...)

#include <iostream>

using namespace std;

int main () {

char c;
cin >> c;
cout << (int)c << endl;

}

if you just have digits, you can do this:

int num = c - '0';
Rasool
  • 286
  • 3
  • 11