前言
在 C/C++程序中,会需要把数字与字符串做出互相转换的操作,用于实现程序想要的效果。下面将介绍多种方法实现数字与字符串互相转换。
字符串转为数字
一、利用 ASCII
我们知道每个字符都有一个 ASCII 码,利用这一点可以将字符-'0'转为数字。在字母大小写转换时也可以利用这个性质。
#include <iostream>
#include <cstring>
using namespace std;
char ch[]={'1','2','3','4','5'};
int main(){
for(int i=0;i<strlen(ch);i++){
cout << ch[i]-'0' << " ";
}
return 0;
}
输出 int 类型的 1,2,3,4,5
二、stoi()
stoi 函数是 C++标准库中的一个函数,用于将字符串转换为整数,针对于 string 类型的。stoi 函数是 C++11 引入的,因此只有在 C++11 及以上的版本中才能使用该函数。
int num = stoi(const string& str, size_t* idx = 0, int base = 10);
其中,str 是需要转换的字符串;idx 是一个指向 size_t 类型的指针,用于保存转换结束的位置;base 是进制,默认为 10 进制。一般只给传第一个参数即可,也可以利用此函数实现进制转换。
类似的还有 stol()、stof()、stod(),分别将字符串类型转换成 long long、float、double 类型。
#include <iostream>
#include <string>
using std;
string s=;
{
a = (s);
b = (s);
c = (s);
d = (s);
cout << << a << endl;
cout << << b << endl;
cout << << c << endl;
cout << << d << endl;
;
}


