string 转换到int型
如果转换的是单个数字
string s = "1234";
s += "null";
std::cout << s[1] << std::endl; //用[]重载得到的元素是char类型的一个元素
auto b = s[1];//得到一个字符
std::cout <<typeid(b).name()<< std::endl;
int c = b - '0'; //'1'通过减去'0'的字符可以自动转到int;
同时转换多位数字
- 使用stoi(),注意接受的参数类型是string
string s = "1234";
int i_from_s = stoi(s);
- atoi() ,注意接受的参数类型是const char*
int i_from_s = atoi(s.c_str());//如果直接放s就会出错
int型转换到string
string to_string (int val);
int i=123;
string s=to_string(i);
补充:使用数据流进行转换
相比c库的转换,它更加安全,自动和直接。
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::stringstream stream;
std::string result;
int i = 1000;
stream << i; //将int输入流
stream >> result; //从stream中抽取前面插入的int值
std::cout << result << std::endl; // print the string "1000"
}