欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数值与字符串之间的相互转化

程序员文章站 2024-03-18 14:10:10
...

方法一:stringstream

//数值转字符串 
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main(){
    double a = 123.56;
    string temp;
    stringstream s;
    s << a;
    s >> temp;//或者 temp = s.str();
    
    cout << temp;
    
    return 0;
}
//字符串转数值 
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main(){
    string str = "123.56";
    double d;
    stringstream s;
    
    s << str;
    s >> d;
    
    cout << d;
    
    return 0;
}

上述方法虽然操作简单,但是运行速度较慢,不值得推荐


方法二:to_string()

#include<iostream>
#include<string>

using namespace std;

int main()
{
	int i=123;
	string s=to_string(i) + "abc"; //float等类型同理

    cout<<s<<endl;
	
	return 0;
}

C++11新增的函数,使用方便。但是在有些平台不支持,比如Dev。

方法三:sprintf sscanf


//数值转字符串
#include<iostream>
#include<string>
#include <stdio.h>

using namespace std;

int main()
{
	char str[20];
	double a=1234.5;
	sprintf(str,"%.1lf",a);
	
	string s = str; //转为string类型 
	
	cout << s;
	
	return 0;
}
//字符串转数字 

#include<iostream>
#include<string>
#include <stdio.h>

using namespace std;

int main()
{
	char str[]= "123456"; 
	int a; 
	sscanf(str, "%d", &a); //换成%x等可以实现进制之间的转换
	
	cout << a;
	
	return 0;
}
//字符串转数字 
#include<iostream>
#include<string>
#include <stdio.h>

using namespace std;

int main()
{
	char str[]= "123.456"; 
	double a; 
	sscanf(str, "%lf", &a); //换成%X之类可以实现进制之间的转换
	
	cout << a;
	
	return 0;
}
使用也比较方便,推荐