gpt4 book ai didi

c++将用户输入double转换为带十进制的字符串

转载 作者:行者123 更新时间:2023-11-28 06:28:28 25 4
gpt4 key购买 nike

大家好,我正在尝试将用户输入的 double 转换为字符串并与其他字符串连接,但是 double 不包含后面的 .00。例如,如果我输入 72.98,它会正确打印出 72.98,但是当我输入 72.00 时,它只会打印出 72 而没有 .00。我怎样才能确保 .00 在那里。

string desc, date;
double amount;
.
.
.
cout << "Enter expenses amount: ";
cin >> amount;
//print to see the amount
cout << amount << endl;
.
.
.
string amt;
amt = static_cast<ostringstream*>( &(ostringstream() << amount) )->str();

string input = desc + ":" + amt + ":" + date;

我试过下面的代码但效果不佳,它给出了一些有趣的数字

stringstream amtstr;
amtstr << setprecision(2) << fixed << amount;
cout << amtstr << endl;;

最佳答案

您的 stringstream 方法有效。你只是在写的时候不打印它的内容

cout << amtstr << endl;

相反,此代码打印stringsteam 对象本身。这被定义为打印对象的地址,而不是字符串内容。

您可以使用str() 成员函数访问字符串内容,例如:

cout << amtstr.str() << endl;

查看此 live demo .

关于c++将用户输入double转换为带十进制的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28111727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com