C++. 字符串和其他类型的相互转化:函数 "stringstream"

函数:"stringstream" 包含在头文件<sstream>中,具体的使用方法如下:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
	
int main(){
	string  str = "124821";
	int n;
	stringstream ss;
	ss << str;
	ss >> n;
    cout << n <<endl;
    return 0;
}

输出结果: 124821;


对比于函数:scanf_s :

scanf_s也能实现从字符串到其他类型的转化,如下:

#include <iostream>
#include <string>
#include <sstream>
#include<stdio.h>
using namespace std;

int main(){
	int n;
	sscanf_s("124824", "%d", &n);
	cout << n;
	return 0;
}

输出结果: 124824

然而,sscanf_s的目标只能是字符指针的常量类型,即const char *类型,对于string没有办法如下图:

C++. 字符串和其他类型的相互转化:函数 "stringstream"

由以上描述可以看出,stringstream 函数更加适合在C++中,对string 类型的字符串和其他类型的相互转化