为什么我不能将“fixed”和“setprecision()”与 +operator 一起使用将其格式化为字符串,而我只能将它与 less-than-less-than-operator 一起使用来格式化它对于 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;
}
最佳答案
Why can't I use "fixed" and "setprecision()" with the +operator to format it into a string?
仔细看看std::fixed
和 std::setprecision()
.
std::fixed
的完整签名:
std::ios_base& fixed(std::ios_base& str);
因此,它专门用于处理流。
在 std::setprecision()
的情况下,它有点棘手:
/*unspecified*/ setprecision( int n );
但是:
Returns an object of unspecified type such that if str is the name of an output stream of type std::basic_ostream or an input stream of type std::basic_istream, then the expression str << setprecision(n) or str >> setprecision(n) behaves as if the following code was executed:
str.precision(n);
因此,如果有一个 std::string::precision()
方法但没有一个方法,它可能会起作用。
What are other ways I can implement this?
可能的解决方案:
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
double a = 157.2734;
cout << "This number is " << fixed << setprecision(1) << a << "." << endl;
ostringstream fmtStr;
fmtStr << "This number is " << fixed << setprecision(1) << a << ".\n";
string line = fmtStr.str();
cout << line;
return 0;
}
输出:
This number is 157.3.
This number is 157.3.
关于c++ - 为什么我不能将 fixed 和 setprecision() 与 +operator 一起用于字符串而不是 << operator 用于 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945591/