std::stringstream中的小数点?

37

我有一堆整数,我把它们放进了 stringstream 中。现在我想将这些 stringstream 转换为 string,同时保持字符串的常量精度。我该如何做?我知道可以使用 stringstreams.precision(),但由于某种原因它不起作用:

float a = 5.23;
float b = 3.134;
float c = 3.0;

std::stringstream ta;
std::stringstream tb;
std::stringstream tc;

ta << a;
tb << b;
tc << c;

ta.precision(2);
tb.precision(2);
tc.precision(2);

std::string out = "";
out += ta.str() + "\n";
out += tb.str() + "\n";
out += tc.str() + "\n";

将返回5.23\n3.134\n3.0,而不是5.23\n3.13\n3.00

3个回答

60

我认为你的问题在于precision()设置了未来流插入操作中使用的精度,而不是在生成最终呈现字符串时。也就是说,通过编写:

ta << a;
tb << b;
tc << c;

ta.precision(2);
tb.precision(2);
tc.precision(2);

您将precision设置得太晚了,因为前三行已经使用默认精度将浮点数转换为字符串。

要解决此问题,请尝试更改执行这些语句的顺序为

ta.precision(2);
tb.precision(2);
tc.precision(2);

ta << a;
tb << b;
tc << c;

这将导致写入到 stringstream 的内容使用您自定义的精度而不是现有的默认值。
然而,precision 修饰符的效果仅在您明确告知流要使用固定精度或科学计数法输出时才有意义。为此,您可以使用 fixedscientific 修饰符:
ta.precision(2);
tb.precision(2);
tc.precision(2);

ta << fixed << a;
tb << fixed << b;
tc << fixed << c;

这将正确显示适当数量的数字。

另外,您不需要使用三个 stringstream 来实现您的目标。您只需要使用一个:

std::stringstream t;
t.precision(2);

t << fixed << a << '\n' << b << '\n' << c << '\n';

std::string out = t.str();

3
谢谢,但还是不行。我仍然得到 3.0 而不是 3.00 - noobcpp
@noobcpp- 哎呀!我的错。我刚更新了这个内容,提到你需要在stringstreams上使用fixed或者scientific模式。尝试进行更改并查看是否解决了问题。 - templatetypedef
+1. @noobcpp:还可以查看一下:http://www.cplusplus.com/reference/iostream/ios_base/precision/(虽然他们说在出现编译器错误的地方使用0)。 - Merlyn Morgan-Graham
16
你不需要将precision 函数单独放在一行上: t << setprecision(2) << fixed << a ... - user470379
6
两年后,这篇帖子仍在挽救生命!感谢 @templatetypedef。 - Hanlet Escaño
#include <iostream> #include <sstream> #include <iomanip> std::stringstream ss; ss << std::setprecision(2) << std::fixed << my_float; std::cout << ss.str() << std::endl; - CIsForCookies

8

在C++20中,您可以使用std::format,它比std::stringstream更加高效且代码更简洁:

float a = 5.23;
float b = 3.134;
float c = 3.0;
std::string out = std::format("{:.2f}\n{:.2f}\n{:.2f}\n", a, b, c);

与此同时,您可以使用{fmt}库std::format基于它(godbolt)。

免责声明:我是{fmt}和C++20 std::format的作者。


1

在将数据传递给stringstream之前,您需要设置fixedprecision。这是您想要完成的工作的一个可行示例:

#include <iostream>
#include <sstream>

using namespace std;

int main(){
    float a = 5.23;
    float b = 3.134;
    float c = 3.0;

    std::stringstream ss;
    ss.setf(std::ios::fixed);
    ss.precision(2);
    
    ss << a << "\n";
    ss << b << "\n";
    ss << c << "\n";
    cout<<ss.str()<<endl;

    return 0;
}

输出:

5.23
3.13
3.00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接