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

it2022-05-08  10

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)