C++中string和int的相互转换
int转string
1. std::to_string()
#include <iostream>
#include <string>
int main()
{
int num = 123;
std::cout << std::to_string(num);
return 0;
}
这种方式在 C++11 中才能使用。
2. stringstream 流方法
#include <iostream>
#include <string>
#include<sstream>
using namespace std;
int main() {
stringstream stream; //声明流对象。
cout << "string转int" << endl;
int n;
string str = "1234";
stream << str;
stream >> n;
cout << "stringstream string转int: " << n << endl;
stream.clear(); //同一个流对象两次使用时应该用clear函数清除流标志,否则下一块就不起作用,这应该是一个程序员的基本素养。
cout << "int转string" << endl;
string str1;
int n1 = 5678;
stream << n1;
stream >> str1;
cout << "stringstream int转string: " << str1 << endl;
return 0;
}
注意:漏斗原则:有数据的>>无数据的
此函数不仅可以实现 string->int ,还可以实现 int->string 的转换。也能实现 string 向 char 的转换:
#include <iostream>
#include <string>
#include<sstream>
using namespace std;
int main() {
stringstream stream;
cout << "string转char[]" << endl;
char ch[10];
string str = "1234";
stream << str;
stream >> ch;
cout << "stringstream string转char: " << ch << endl;
return 0;
}
string 转 int
1. stringstream 流方法
如上 int 转 string 中所述
2. stoi()函数
#include<iostream>
#include<string>
using namespace std;
int main() {
string s = "123";
int num = stoi(s);
cout << typeid(num).name() << " " << num << endl;
return 0;
}
3. stol() 函数
此函数将在函数调用中作为参数提供的字符串转换为long int
long int stol(const string&str,size_t * idx = 0,int base = 10)
参数: 该函数接受三个参数:
str:它指定一个字符串对象,并以整数表示。
idx:它指定一个指向size_t类型的对象的指针,该指针的值由函数设置为数值之后str中下一个字符的位置。该参数也可以是空指针,在这种情况下不使用它。
base:指定数字基数,以确定用于解释字符的数字系统。如果基数为0,则要使用的基数由序列中的格式确定。预设值为10。
返回值:该函数将转换后的整数返回为long int类型的值。
#include<iostream>
#include<string>
using namespace std;
int main() {
string s = "987654321";
cout << "s = " << stol(s) << endl;
cout << "s = " << stol(s, nullptr, 10) << endl;
return 0;
}
4. stoll() 函数
此函数将在函数调用中作为参数提供的字符串转换为long long int
long long int stoll(const string&str,size_t * idx = 0,int base = 10)
参数:该函数接受三个参数:
str:此参数指定带有整数的String对象。
idx:此参数指定指向size_t类型的对象的指针,该对象的值由功能设置为数值后str中下一个字符的位置。此参数也可以是空指针,在这种情况下,将不使用该参数。
base:此参数指定数字基数,以确定用于解释字符的数字系统。如果基数为0,则它使用的基数由序列中的格式确定。默认基数为10。
返回值:该函数将转换后的整数作为long long int类型的值返回。
#include<iostream>
#include<string>
using namespace std;
int main() {
string s = "9876543210";
cout << "s = " << stoll(s) << endl;
cout << "s = " << stoll(s, nullptr, 10) << endl;
return 0;
}

浙公网安备 33010602011771号