C++ 如何将单个字符转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/439573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:21:21  来源:igfitidea点击:

How to convert a single char into an int

c++char

提问by jonsb

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?

我有一串数字,例如“123456789”,我需要提取每个数字以在计算中使用它们。我当然可以通过索引访问每个字符,但是如何将其转换为整数?

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?

我已经研究过 atoi(),但它需要一个字符串作为参数。因此,我必须将每个字符转换为字符串,然后对其调用 atoi。有没有更好的办法?

回答by Binary Worrier

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

您可以利用这样一个事实,即数字的字符编码都是从 48(对于 '0')到 57(对于 '9')的顺序。这适用于 ASCII、UTF-x 和几乎所有其他编码(有关更多信息,请参阅下面的评论)。

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

因此,任何数字的整数值都是数字减去“0”(或 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.

但是我发现第一个c - '0'更具可读性。

回答by Antonius RC

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

回答by jalf

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 方法,但使用 std::stringstream 代替。这应该适用于字符作为输入以及字符串。(boost::lexical_cast 是另一种更方便语法的选项)

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

(atoi 是一个旧的 C 函数,通常建议在可能的情况下使用更灵活和类型安全的 C++ 等效函数。std::stringstream 涵盖了与字符串的转换)

回答by arun.rajput

You can make use of atoi() function

您可以使用 atoi() 函数

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

回答by Douglas Leeder

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.

只要您只想处理阿拉伯数字,并且在这些数字是连续的编码中工作,并且与 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.

让我们从ICU开始。

  1. First convert the byte-string to a unicode string. (Left as an exercise for the reader).
  2. Then use uchar.hto 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 )
  1. 首先将字节字符串转换为 unicode 字符串。(留给读者作为练习)。
  2. 然后使用uchar.h查看每个字符。
  3. 如果我们的角色是 UBool u_isdigit (UChar32 c)
  4. 那么值是 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.

或者也许ICU有一些功能可以为你做这件事——我没有详细研究过。

回答by Douglas Leeder

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

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

回答by Ravi Singh

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

通过这种方式,您可以轻松地将 char 转换为 int 并将 int 转换为 char:

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

回答by jonsb

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;
    }
}

回答by user54650

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

如果你正在担心编码,你可以随时使用switch语句。

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)

请注意保留这些大数字的格式。某些系统中整数的最大大小低至 65,535(有符号的 32,767)。其他系统,您有 2,147,483,647(或 4,294,967,295 未签名)

回答by KYL3R

For me the following worked quite well:

对我来说,以下工作非常好:

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

Documentation: int QChar::digitValue() constwhich says:

文档:int QChar::digitValue() const其中说:

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

返回数字的数值,如果字符不是数字,则返回 -1。