c++ - 为什么我不能将 fixed 和 setprecision() 与 +operator 一起用于字符串而不是 << operator 用于 cout

标签 c++ string operator-keyword fixed iomanip

为什么我不能将“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::fixedstd::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.

Life demo on ideone

关于c++ - 为什么我不能将 fixed 和 setprecision() 与 +operator 一起用于字符串而不是 << operator 用于 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945591/

相关文章:

c++ - `operator()...`在C++代码中是什么意思?

python - Python 中的新运算符

c++ - 我必须重载哪个运算符?

c++ - 模板函数不接受原始类型?

c++ - 从txt文件C++读取浮点错误值

python - 用 Python 解析 'time string'?

javascript - 使用多个三元运算符替换字符串的多个字符

c++ - 我如何将我的程序变成我可以安装的东西?

python - 具有类成员的 pybind11 缓冲协议(protocol)

java - 如何从这个字符串中解析出时间戳?