C++17继续完善了字符串和数值的转换,提供了char*与数值件的转换:
数值 -> char*
整形类型转成字符串:
to_chars_result to_chars(char* first, char* last, IntegerT value, int base = 10);
浮点数转成字符串:
to_chars_result to_chars(char* first, char* last, FloatT value);
to_chars_result to_chars(char* first, char* last, FloatT value, chars_format format);
to_chars_result to_chars(char* first, char* last, FloatT value, chars_format format, int precision);
[first, last)为存储转换结果的连续内存区间。
函数返回值为:
struct to_chars_result {
char* ptr;
errc ec;
};
如果转换成功的话,ptr为写入到[first, last)的最后一个字符的下一个地址,ec值等于std::errc()。
如果转换不成功的话,ptr值为last,ec的值不等于std::errc()。
值得注意的是to_chars不会写入字符串结束符\0。
#include
#include
#include
using namespace std;
auto pRet = [](auto ptr, auto ec, char* str)
{
if (ec == errc())
{
cout << "to_chars ok str=" << str << " ptr=" << ptr << endl;
}
else
{
cout<< "to_chars failed"<
char* -> 数值
from_chars_result from_chars(const char* first, const char* last, IntegerT& value, int base = 10);
from_chars_result from_chars(const char* first, const char* last, FloatT& value, chars_format format = chars_format::general);
[first, last):要装换的字符串
base:进制
返回值与to_chars相同
#include
#include
using namespace std;
int main()
{
char s1[] = "1234a";
char s2[] = " 5678";
int i1 = 0, i2 = 0;
auto [ptr1, ec1] = from_chars(s1, s1+sizeof(s1), i1);
if (ec1 == errc())
{
cout << "from_chars ok i1=" << i1 << " ptr1=" << ptr1 << endl;
}
else
{
cout<< "from_chars failed"<<" ptr1=" << ptr1 << endl;
}
auto [ptr2, ec2] = from_chars(s2, s1+sizeof(s2), i2);
if (ec2 == errc())
{
cout << "from_chars ok i2=" << i2 << " ptr2=" << ptr2 << endl;
}
else
{
cout<< "from_chars failed"<<" ptr2=" << ptr2 << endl;
}
return 0;
}
运行程序输出:
from_chars ok i1=1234 ptr1=a
from_chars failed ptr2= 5678
可见,from_chars不能忽略字符串开头的空白