将char转换为int' 23' > 23

时间:2015-03-28 11:19:47

标签: c++ char int typeconverter

我看过如此多的关于如何将单个数字转换为int的帖子,但我如何将多个数字转换为int,就像' 23'将其转换为23;

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

使用内置函数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] != '\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;
}

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

相关问题