【问题标题】:Converting char to int '23' > 23将 char 转换为 int '23' > 23
【发布时间】:2015-03-28 11:19:47
【问题描述】:

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

【问题讨论】:

标签: c++ char int typeconverter


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    使用内置函数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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 2011-02-25
      相关资源
      最近更新 更多