Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::ostringstream将标志放置在错误的位置?_C++ - Fatal编程技术网

C++ std::ostringstream将标志放置在错误的位置?

C++ std::ostringstream将标志放置在错误的位置?,c++,C++,我使用std::ostringstream将double格式化为具有特定格式的字符串(使用撇号作为分隔符)。然而,在某些情况下,ostringstream给了我一个与我预期不同的结果 据我所知,下面代码的预期输出应该是“+01”;相反,它输出“0+1”。我做错了什么?我怎样才能得到我需要的结果 #include <iomanip> #include <iostream> #include <sstream> int main() { std::os

我使用std::ostringstream将double格式化为具有特定格式的字符串(使用撇号作为分隔符)。然而,在某些情况下,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;
}
#包括
#包括
#包括
int main()
{
std::奥斯汀溪流;

流不幸的是,这就是它的工作原理。“0”用作填充字符,而不是数字的一部分

要解决此问题,必须分别输出+或-:

std::ostringstream oss;
oss << "+-"[x<0];
oss << std::setw(2) << std::setfill('0') << std::abs(x);
return/cout/whatever oss.str();
std::ostringstream oss;

oss填充有三个选项

您需要在符号和值之间进行
internal
填充

stream << std::setfill( '0' ) << std::internal; // Zero-padded

stream您可以使用
std::internal
juste-before
std::showpos
(如图所示)

我们需要添加std::internal标志来告诉流插入“internalpadding”——即,应该在符号和数字的其余部分之间插入填充

#包括
#包括
#包括
int main()
{
std::奥斯汀溪流;

stream填充字符与any类型一起使用,以填充给定的宽度。默认情况下,填充字符位于值的左侧,这就是这些零所看到的。解决方案是覆盖该默认值,并告诉流将填充字符放入文本中:

std::cout << std::internal << std::setfill(0) << std::setw(3) << 1 << '\n';

std::cout只需几个字符,
oss=0?:“+”:“-”);
在我看来会更具可读性。可以得到PO想要的东西。只需看看@Pete Becker或我的答案。
std::cout << std::internal << std::setfill(0) << std::setw(3) << 1 << '\n';