C++ 中数字间进制转换输出,string和数字的转换,string和C字符间的转换

string和数字的转换

函数:to_string(),将数字转换为string

#include<iostream>
#include<string>
using namespace std;
int main() {
	int a = 1;
	double b = 0.1;
	cout << b << endl;
	string str_int,str_dou;
	str_int = to_string(a);
	str_dou = to_string(b);//此处double类型默认精度为小数点后6位,例如3.1,3.100000  3.12345678,3.123456
	str_dou.erase(str_dou.find_last_not_of("0")+1);//去掉多余的精度零,其中find_last_not_of(“0”)返回字符串中最后一个非零的数字的位置,之后的精度零都删去
	cout << str_int << " " << str_dou;
}

数字间进制转换输出

#include<iostream>
#include<string>
#include<bitset>
using namespace std;
int main() {
	int a = 7;
	bitset<sizeof(int) * 4> bin;
	bin = bitset<sizeof(int) * 4>(a);//此处将十进制int整数,转换成二进制的bitset类型
	cout << bin;//输出为32位二进制
	cout << endl;
	string bin_str = bin.to_string();//此处将bitset类型转换为string
	bin_str = bin_str.substr(bin_str.find_first_not_of("0"));//将二进制前面的0删去
	cout << bin_str << endl;

	//将十进制转换位16进制输出
	int b = 12;
	cout << hex;
	cout << b << endl;
	//转换位八进制
	cout << oct;
	cout << b << endl;
	//恢复十进制
	cout << dec;
	cout << b << endl;
	return 0;
}

string转换C字符串

函数:c_str()

#include<iostream>
#include<string>
#include<bitset>
using namespace std;
int main() {
	string a{ "hello world" };
	const char * str_const = a.c_str();//返回的是常字符串
	char * str = const_cast<char *>(str_const);//使用const_cast将常字符串转化为普通字符串
	cout << str << endl;
	char str1[] = "bye world";
	str = str1;
	cout << str << endl;
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值