【发布时间】:2018-08-03 09:02:02
【问题描述】:
为什么我不能将“fixed”和“setprecision()”与 + 运算符一起使用来将其格式化为字符串,而我只能将其与小于小于运算符一起使用来格式化它为 cout。我可以通过哪些其他方式来实现它?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a = 157.2734;
cout << "This number is " << fixed << setprecision(1) << a << "." << endl;
string line = "This number is " + fixed + setprecision(1) + a + "." + "\n"; // This doesn't work this way! Why!?!?!?
cout << line;
return 0;
}
【问题讨论】:
-
std::fixed和std::setprecision()是流的操纵器。您可以改为使用std::ostringstream格式化字符串。 -
它叫stream insertion operator
<<,而不是less-than-less-than-operator。 -
除了@Ron 最初,
<<和>>是位移运算符。它们已被流“滥用”(通过重载)。 -
@Ron,其实是移位运算符。
-
这是一个公平的问题,因为它看起来确实不一致,但在幕后,您的两个陈述正在做非常不同的事情。流方法重载
<<运算符,字符串重载+进行连接。
标签: c++ string operator-keyword fixed iomanip