数值类型和字符串之间的转换

在C++11中提供了专门的数值类型和字符串类型之间的转换的转换函数。

数值转换为字符串

使用to_string()方法可以将各种数值类型转换为字符串类型,这是一个重载函,函数声明位于头文件 中,函数原型如下:

// 头文件 <string>
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

用例:

#include <iostream>
#include <string>
using namespace std;

//数值传字符串类型
void numberToString() {
	long double dd = 3.1315926789;
	string pi = "pi is " + to_string(dd);
	string love = "love is " + to_string(13.14);
	cout << pi << endl;
	cout << love << endl << endl;
}
int main() {
	numberToString();
	system("pause");
	return 0;
}

输出结果:

pi is 3.131593
love is 13.140000

字符串转换为数值

C++针对于不同的类型提供了不同的函数,通过调用这些函数可以将字符串类型转换为对应的数值类型。

// 定义于头文件 <string>
int       stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
long      stol( const std::string& str, std::size_t* pos = 0, int base = 10 );
long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 );

unsigned long      stoul( const std::string& str, std::size_t* pos = 0, int base = 10 );
unsigned long long stoull( const std::string& str, std::size_t* pos = 0, int base = 10 );

float       stof( const std::string& str, std::size_t* pos = 0 );
double      stod( const std::string& str, std::size_t* pos = 0 );
long double stold( const std::string& str, std::size_t* pos = 0 );

其中参数含义:

​ str:要转换的字符串。

​ pos:传出参数,记录从哪个字符开始无法继续进行转化;比如 123a32,就是在a的时候无法继续转换,传出位置就是3,即pos为a的地址。】

​ base:用于指明前面参数str的进制(是说str是几进制,转换后的结果都是10进制) 若base为0,则自动检测数值进制(若前缀为0,则为八进制,若前缀为0x或0X,则为十六进制,否则为十进制。

这些函数虽然都有多个参数,但是除去第一个参数外其他都有默认值,一般情况下使用默认值就能满足需求。

关于函数的使用也给大家提供了一个例子,示例代码如下:

#include <iostream>
#include <string>
using namespace std;

//字符串转数值类型
void stringToNumber() {
	string str_dec = "2022.02.04, Beijing Winter Olympics";
	string str_hex = "40c3";
	string str_bin = "-10010110001";
	string str_auto = "0x7f";

	size_t sz; // size_t是c++标注库中定义的类型,本质是无符号整型;专门用来表示:对象大小、内存大小、字符串长度、数组下标。
	int i_dec = stoi(str_dec, &sz);
	int i_hex = stoi(str_hex, nullptr, 16);
	int i_bin = stoi(str_bin, nullptr, 2);
	int i_auto = stoi(str_auto, nullptr, 0); //写0是让计算机自己推导。

	cout << "..... sz = " << sz << endl;
	cout << str_dec << ": " << i_dec << endl;
	cout << str_hex << ": " << i_hex << endl;
	cout << str_bin << ": " << i_bin << endl;
	cout << str_auto << ": " << i_auto << endl;
}

int main() {
	stringToNumber();
	system("pause");
	return 0;
}

输出结果:

..... sz = 4
2022.02.04, Beijing Winter Olympics: 2022
40c3: 16579
-10010110001: -1201
0x7f: 127

所以转换过程就是 转换到不能转换的字符停止。

原文链接:数值类型和字符串之间的转换

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容