c++怎样把double转为string

2025-02-24 00:31:05
推荐回答(3个)
回答1:

如果你会用printf,那sprintf也不难理解:

#include 
#include 
using namespace std;
int main() {
    double d = 12345.6789;
    char buf[256] = "";
    sprintf(buf, "%lf", d);
    cout << buf << endl;
    
    string str = buf;
    cout << str << endl;
    return 0;
}

另外再推荐一个stringstream:

#include 
#include 
#include 
using namespace std;

string toString(double d) {
    stringstream ss;
    // 默认浮点数只输出6位有效数字,这里改成小数点后6位
    ss.setf(ios::fixed);
    ss << setprecision(6) << d;
    return ss.str();
}

int main() {
    double d = 12345.6789;
    cout << toString(d) << endl;
    
    return 0;
}

用stringstream还可以有奇效哦!比如加上模板:

#include 
#include 
#include 
using namespace std;

template
string toString(T t) {
    stringstream ss;
    ss.setf(ios::fixed);
    ss << setprecision(6) << t;
    return ss.str();
}

int main() {
    // 浮点数变成字符串
    double d = 12345.6789;
    cout << toString(d) << endl;
    
    // 整数变成字符串
    int i = 12345;
    cout << toString(i) << endl;
    
    // 字符变成字符串
    char ch = 'A';
    cout << toString(ch) << endl;
    
    // 指针地址变成字符串
    void *p = &i;
    cout << toString(p) << end;
    
    return 0;
}

回答2:

在Windows系统下的转换方法 windows下进行此类一般使用sprintf_s函数,使用该函数需要包含头文件stdio.h。 示例:例如我要将 1.234567 这个小数转化为字符串"1.234567“。首先,要包含头文件 cstdio(即 stdio.h)。

回答3:

ftoa:浮点数强制成字符串, 这个不是C标准库中的函数,而是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,用法跟printf类似: char str[255]; sprintf(str, "%f", 10.8); //将10.8转为字符串 c++中有itoa,没有ftoa,