How to convert a single char into an int

C++Char

C++ Problem Overview


I have a string of digits, e.g. "123456789", and I need to extract each one of them to use them in a calculation. I can of course access each char by index, but how do I convert it into an int?

I've looked into atoi(), but it takes a string as argument. Hence I must convert each char into a string and then call atoi on it. Is there a better way?

C++ Solutions


Solution 1 - C++

You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).

Therefore the integer value for any digit is the digit minus '0' (or 48).

char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'

is synonymous to

char c = '1';
int i = c - 48; // i is now equal to 1, not '1'

However I find the first c - '0' far more readable.

Solution 2 - C++

#define toDigit(c) (c-'0')

Solution 3 - C++

Or you could use the "correct" method, similar to your original atoi approach, but with std::stringstream instead. That should work with chars as input as well as strings. (boost::lexical_cast is another option for a more convenient syntax)

(atoi is an old C function, and it's generally recommended to use the more flexible and typesafe C++ equivalents where possible. std::stringstream covers conversion to and from strings)

Solution 4 - C++

You can make use of atoi() function
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]){
    int num ;
    num = atoi(argv[1]);
    printf("\n%d", num);
}

Solution 5 - C++

The answers provided are great as long as you only want to handle Arabic numerals, and are working in an encoding where those numerals are sequential, and in the same place as ASCII.

This is almost always the case.

If it isn't then you need a proper library to help you.

Let's start with ICU.

  1. First convert the byte-string to a unicode string. (Left as an exercise for the reader).
  2. Then use uchar.h to look at each character.
  3. if we the character is UBool u_isdigit (UChar32 c)
  4. then the value is int32_t u_charDigitValue ( UChar32 c )

Or maybe ICU has some function to do it for you - I haven't looked at it in detail.

Solution 6 - C++

#include<iostream>
#include<stdlib>
using namespace std;

void main()
{
     char ch;
     int x;
     cin >> ch;
     x = char (ar[1]);
     cout << x;
}

Solution 7 - C++

If you are worried about encoding, you can always use a switch statement.

Just be careful with the format you keep those large numbers in. The maximum size for an integer in some systems is as low as 65,535 (32,767 signed). Other systems, you've got 2,147,483,647 (or 4,294,967,295 unsigned)

Solution 8 - C++

Any problems with the following way of doing it?

int CharToInt(const char c)
{
	switch (c)
	{
	case '0':
		return 0;
	case '1':
		return 1;
	case '2':
		return 2;
	case '3':
		return 3;
	case '4':
		return 4;
	case '5':
		return 5;
	case '6':
		return 6;
	case '7':
		return 7;
	case '8':
		return 8;
	case '9':
		return 9;
	default:
		return 0;
	}
}

Solution 9 - C++

By this way You can convert char to int and int to char easily:

int charToInt(char c)
{
   int arr[]={0,1,2,3,4,5,6,7,8,9};
   return arr[c-'0'];
}

Solution 10 - C++

I agree with @jalf. Using the sstream library and stoi appears to be the recommended approach:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

  stringstream st;
  st << 1  << '2';

  cout << stoi(st.str()) + 1; 

  return 0;
}

Output

13

I am a new student of C++ but a long-time LAMP stack developer. I was hoping the string class had more things to smoothly transition between chars and strings, but I've not yet found such a thing that is natively supported.

Solution 11 - C++

For me the following worked quite well:

QChar c = '5';
int x = c.digitValue();
// x is now 5

Documentation: int QChar::digitValue() const which says:

> Returns the numeric value of the digit, or -1 if the character is not > a digit.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjonsbView Question on Stackoverflow
Solution 1 - C++Binary WorrierView Answer on Stackoverflow
Solution 2 - C++Antonius RCView Answer on Stackoverflow
Solution 3 - C++jalfView Answer on Stackoverflow
Solution 4 - C++arun.rajputView Answer on Stackoverflow
Solution 5 - C++Douglas LeederView Answer on Stackoverflow
Solution 6 - C++haidernuteView Answer on Stackoverflow
Solution 7 - C++user54650View Answer on Stackoverflow
Solution 8 - C++jonsbView Answer on Stackoverflow
Solution 9 - C++Ravi SinghView Answer on Stackoverflow
Solution 10 - C++Spencer WilliamsView Answer on Stackoverflow
Solution 11 - C++KYL3RView Answer on Stackoverflow