c ++将用户输入double转换为带小数的字符串

时间:2015-01-23 14:08:21

标签: c++ string 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;;

3 个答案:

答案 0 :(得分:1)

您的stringstream方法有效。您只是在编写

时不打印其内容
cout << amtstr << endl;

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

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

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

请参阅此live demo

答案 1 :(得分:0)

您的编译器是否支持std::to_string

auto input = std::to_string(myDouble);
if (input.find(".") == std::string::npos) {
    input += ".00";
}
else {
    input = input.substr(0, input.find(".") + 3);
}

答案 2 :(得分:0)

您可以使用旧的C风格格式。

char szBuffer[64];
sprintf(szBuffer, "%.2f", amount);
std::string amt = szBuffer;
相关问题