C++ 字符串与数值间的转换(只归纳了常用情况)

发布时间 2023-11-03 16:35:48作者: 少玩手机

很多编程中 字符串与数字间的转换是一种常见的需求 下面总结了C++中字符串与数值间是如何进行转换的。

目录:

1. 字符串转数字(C版本)
2. 字符串转数字C++风格
3. 数字转字符串

1.字符串转数字(C版本)

    string s1 = "123";
    string s2 = "123.1";
    int i = atoi(s1.c_str());
    double d = atof(s2.c_str());
    cout<<i<<endl;
    cout<<d<<endl;

上述中的库函数 atoi atof 均在stdlib.h的头文件中声明 函数原型如下:

  	double	 atof(const char *);
	int	 atoi(const char *);
	long	 atol(const char *);

不难看出,上面这些方法的输入均为const char *,即字符串,得到的输出为转化以后的各种数值类型。

运行结果:
123
123.1

  1. 字符串转数字(C++版本)
    void func2() {
    string s1 = "456";
    string s2 = "456.2";
    int i = stoi(s1);
    long l = stol(s1);
    float f = stof(s2);
    double d = stod(s2);
    cout<<i<<endl;
    cout<<l<<endl;
    cout<<f<<endl;
    cout<<d<<endl;
}

上述库函数均存在于string类中 这些成员函数的原型如下:

 LIBCPP_FUNC_VIS int                stoi  (const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS long               stol  (const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS unsigned long      stoul (const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS long long          stoll (const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS unsigned long long stoull(const string& __str, size_t* __idx = 0, int __base = 10);

_LIBCPP_FUNC_VIS float       stof (const string& __str, size_t* __idx = 0);
_LIBCPP_FUNC_VIS double      stod (const string& __str, size_t* __idx = 0);
_LIBCPP_FUNC_VIS long double stold(const string& __str, size_t* __idx = 0);

运行结果:
456
456
456.2
456.2

3.数字转换成字符串

C++11新特性后,string类提供了to_string()方法,可以将各种类型的数字转换成字符串。

    void func3() {
    int i = 123;
    float f = 1.234;
    double d = 2.012;
    cout<<to_string(i)<<endl;
    cout<<to_string(f)<<endl;
    cout<<to_string(d)<<endl;
}

运行结果:
123
1.234000
2.012000

上述输出结果与我们的预期有差异,原因是与浮点数显示精度有关。
我们可以使用precision来控制精度,在输入输出操作头文件中有声明

#include<sstream>
#include <iomanip>
using namespace std;

void func4() {
    double d = 3.14159265358979;
    cout << d << endl;
    stringstream ss;
    ss.precision(10);
    ss << d;
    cout << ss.str() << endl;
}

运行结果:
3.14159
3.141592654