C++ 将字符转换为int';23'&燃气轮机;23

C++ 将字符转换为int';23'&燃气轮机;23,c++,char,int,typeconverter,C++,Char,Int,Typeconverter,我看过很多关于如何将一个数字转换成整数的帖子,但是我如何将多个数字转换成整数,就像“23”将其转换成23一样 使用内置函数,或编写自己的实现,例如: // A simple C++ program for implementation of atoi #include <stdio.h> // A simple atoi() function int myAtoi(char *str) { int res = 0; // Initialize result //

我看过很多关于如何将一个数字转换成整数的帖子,但是我如何将多个数字转换成整数,就像“23”将其转换成23一样

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

// 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] != '\0'; ++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;
}
<代码> //实现ATOI的一个简单C++程序 #包括 //一个简单的atoi()函数 int myAtoi(字符*str) { int res=0;//初始化结果 //遍历输入字符串的所有字符并更新结果 对于(int i=0;str[i]!='\0';++i) res=res*10+str[i]-“0”; //返回结果。 返回res; } //用于测试上述功能的驱动程序 int main() { 字符str[]=“89789”; int val=myAtoi(str); printf(“%d”,val); 返回0; }
来源:

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

您还可以使用
stoi()
,它为转换提供了一些附加功能,例如指定基