将 char 转换为 int '23' > 23

Converting char to int '23' > 23

我看过很多post如何将单个数字转换为 int,但是我如何将多位数字转换为 int,就像'23'将其转换为 23 一样;

使用内置函数std::stoi,或者自己编写实现,例如:

// A simple C++ program for implementation of atoi
#include <stdio.h>

// A simple atoi() function
int myAtoi(char *str)
{
    int res = 0; // Initialize result

    // Iterate through all characters of input string and update result
    for (int i = 0; str[i] != '[=10=]'; ++i)
        res = res*10 + str[i] - '0';

    // return result.
    return res;
}

// Driver program to test above function
int main()
{
    char str[] = "89789";
    int val = myAtoi(str);
    printf ("%d ", val);
    return 0;
}

来源:http://www.geeksforgeeks.org/write-your-own-atoi/

要将字符数组转换为整数,请使用 atoi()。如果转换字符串,在字符串变量后添加.c_str(),将其转换成适合使用的形式。

您还可以使用 stoi(),它提供了一些额外的转换功能,例如指定基数。