Как преобразовать char в int

от admin

Преобразовать char в int в C#

В этом посте будет обсуждаться, как преобразовать char в int в C#.

1. Использование Char.GetNumericValue() метод

Рекомендуемый подход заключается в использовании встроенного GetNumericValue() метод для преобразования числового символа Unicode в его числовой эквивалент.

Следующий пример демонстрирует работу GetNumericValue() метод. Он ожидает символьное представление числового значения и возвращает двойное значение. Приведение необходимо для преобразования значения double в int.

Как преобразовать char в int

Here we will see how to convert char to int using a C++ program. There are 6 ways to convert char to int in C++:

  1. Using Typecasting.
  2. Using static_cast.
  3. Using sscanf().
  4. Using stoi().
  5. Using atoi().
  6. Using string stream.

Let’s discuss each of these methods in detail.

1. Using Typecasting

Method 1:

  1. Declare and initialize our character to be converted.
  2. Typecast the character to convert character to int using int.
  3. Print the integer using cout.

Below is the C++ program to convert char to int value using typecasting:

If a numeric character needs to be typecasted into the integer value then either we can subtract 48 or ‘0’ and then typecast the numeric character into int.

Below is the C++ program to convert char to integer value using typecasting:

Method 2:

  1. Declare and initialize our character to be converted.
  2. Declare another variable as int N and assign the character ch to the N.
  3. Print the integer using cout.

Below is the C++ program to convert char to int value using typecasting:

2. Using static_cast

The character can be converted to an integer using the static_cast function. Below is the C++ program to convert char to int value using static_cast:

3. Using sscanf

Reads data from s and stores it in the places specified by the additional arguments in the parameter format. Below is the C++ program to convert char to int using sscanf():

4. Using stoi

The stoi() function in C++ converts a string to an integer value. Below is the C++ program to convert char to int using stoi():

5. Using atoi

If the execution is successful, the atoi() method returns the converted integer value. If the given string cannot be converted to an integer, it will return 0. Below is the C++ program to convert char to int using atoi():

6. Using stringstream

A stringstream connects a string object to a stream, allowing you to read from it as if it were a stream (like cin). Stringstream requires the inclusion of the sstream header file. The stringstream class comes in handy when processing input.
Below is the C++ program to convert char to int using string stream:

How to convert a single char into an int [duplicate]

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?

11 Answers 11

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).

is synonymous to

However I find the first c — ‘0’ far more readable.

Binary Worrier's user avatar

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)

You can make use of atoi() function

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.

How To Convert Char to Int in C++

Are you looking to know how to convert Char to Int in C++? This article will show you the different ways to convert Char to Int.

In C++, most of the Char and Integer values can be represented by ASCII [1] values. Hence if you know the ASCII values for the number that are currently represented in char then you can easily convert those into integers.

Convert Char to Int in C++ Using ASCII Values

Let us see the below example code of how you can convert the number represented in Char to an integer value.

Output:

As you can see in the above code, ‘9’ was represented in char, and then with the use of typecasting the char value that reads it in ASCII form and then converts it to an integer value. Hence if you are aware that the char value can be represented in the ASCII value then only you can use this method and it would work.

Convert Char to Int Using Subtraction

This method you can use if you have a character that cannot be represented in ASCII value for example number 20. Hence to convert the char ’20’ in integer we need to use the subtraction method that will provide the ASCII for each digit and then we can add those to get the actual number.

Let us see in the below example code the usage of subtraction to get the Integer from Char in C++.

Output:

As per the above code, example — ‘0’ is equivalent to ((int)example) — ((int)’0′), which means the ASCII values of the characters are subtracted from each other. Since 0 comes directly before 1 in the ASCII table (and so on until 9 ), the difference between the two gives the number that the character a represents.

How To Convert Char to Int in C++

Convert Char* To Int in C++

If you want to convert char* to int in C++ when char* represents the number. And if the char* variable does not represent number then the below methods will not work.

Let us check in below example code below how you can change the char* to Int in C++.

Output:

As you can see in the above I was able to convert the char* to int using the string stream library. But this method is not 100% secure and you will receive a warning in C++ that you should not convert string to char*.

But if you still want to convert the char* to int ignoring the warning then you can use the above code to resolve this problem.

Wrap Up

I hope you got the answer related to how to convert char to int in C++. I have discussed two methods above that you can use directly to do the conversion.

Let me know in the comment section if you have found any method that is better than the one discussed above I will be happy to add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Похожие статьи