我正在使用std :: ostringstream将双精度格式化为具有特定格式的字符串(使用撇号作为数千个分隔符)。但是,在某些情况下,ostringstream给了我不同于我预期的结果。std :: ostringstream放置错误的位置?
据我所知,以下代码的预期输出应为“+01”;而是输出“0 + 1”。我在这里做错了什么,我如何得到我需要的结果?
#include <iomanip>
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream stream;
stream << std::showpos; // Always show sign
stream << std::setw(3); // Minimum 3 characters
stream << std::setfill('0'); // Zero-padded
stream << 1; // Expected output: "+01"
std::cout << stream.str(); // Output: "0+1"
return 0;
}
只有几个字符,'oss << (x> = 0? :'+':' - ');在我看来,'会更具可读性。 – YSC
有可能获得PO想要的。看@Pete Becker的答案或我的。 – informaticienzero