有没有办法打印整数及其符号c ++ ...即。默认情况下,如果数字为负数,我们会打印一个-
符号。同样,我们可以在正数之前得到+
。
int x=-1;
cout<<"x="<<x;
提供输出x=-1
但是,..
int x=+1;
cout<<"x="<<x;
将输出设为x=1
,但如何将其打印为x=+1
我知道我们可以通过if-else
使用x&gt; 0和x&lt; 0; ..而不使用if-else,在c ++中有任何直接的打印方式
答案 0 :(得分:9)
使用std::showpos
:
int x = 1;
std::cout << "x=" << std::showpos << x;
答案 1 :(得分:0)
怎么样:
cout<<"x="<<(x>0)?"+":""<<x;
它有点笨拙,但适合账单
答案 2 :(得分:0)
C ++ 20 std::format
选项+
根据https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification,以下内容应成立:
// "1,+1,1, 1"
std::cout << std::format("{0:},{0:+},{0:-},{0: }", 1);
// "-1,-1,-1,-1"
std::cout << std::format("{0:},{0:+},{0:-},{0: }", -1);
更多信息,请访问:std::string formatting like sprintf