【问题标题】:Why can't I use fixed and setprecision() with +operator for strings instead of <<operator for cout为什么我不能将 fixed 和 setprecision() 与 +operator 用于字符串而不是 <<operator 用于 cout
【发布时间】: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::fixedstd::setprecision() 是流的操纵器。您可以改为使用 std::ostringstream 格式化字符串。
  • 它叫stream insertion operator&lt;&lt;,而不是less-than-less-than-operator
  • 除了@Ron 最初,&lt;&lt;&gt;&gt; 是位移运算符。它们已被流“滥用”(通过重载)。
  • @Ron,其实是移位运算符。
  • 这是一个公平的问题,因为它看起来确实不一致,但在幕后,您的两个陈述正在做非常不同的事情。流方法重载&lt;&lt; 运算符,字符串重载+ 进行连接。

标签: c++ string operator-keyword fixed iomanip


【解决方案1】:

为什么我不能使用“fixed”和“setprecision()”和 + 运算符来将其格式化为字符串?

仔细查看std::fixedstd::setprecision()

std::fixed的完整签名:

std::ios_base& fixed(std::ios_base& str);

因此,它旨在专门用于流。

std::setprecision()的情况下,有点棘手:

/*unspecified*/ setprecision( int n );

但是:

返回一个未指定类型的对象,使得如果 str 是 std::basic_ostream 类型的输出流或 std::basic_istream 类型的输入流的名称,则表达式 str > setprecision(n) 的行为就像执行了以下代码:

  str.precision(n);

所以,如果有 std::string::precision() 方法但没有,它可能会起作用。


还有哪些其他方法可以实现?

可能的解决方案:

#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

【讨论】:

  • 更新:忘记了#include &lt;sstream&gt;。在 ideone (gcc) 中它没有工作,但 with 是正确的。
猜你喜欢
  • 2014-08-30
  • 1970-01-01
  • 2020-08-26
  • 2013-06-19
  • 2016-08-30
  • 1970-01-01
  • 2018-07-30
  • 2021-04-18
  • 1970-01-01
相关资源
最近更新 更多