【发布时间】:2015-03-28 11:19:47
【问题描述】:
我看过很多关于如何将单个数字转换为 int 的帖子,但是我如何将多个数字转换为 int,就像 '23' 将其转换为 23;
【问题讨论】:
标签: c++ char int typeconverter
我看过很多关于如何将单个数字转换为 int 的帖子,但是我如何将多个数字转换为 int,就像 '23' 将其转换为 23;
【问题讨论】:
标签: c++ char int typeconverter
要将 char 数组转换为整数,请使用 atoi()。如果转换字符串,在字符串变量后面加上.c_str(),将其转换成适合使用的形式。
您也可以使用stoi(),它提供了一些额外的转换功能,例如指定基数。
【讨论】:
使用内置函数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;
}
【讨论】: