4

Is there any way to print the integer along with its sign in c++...i.e. by default if the number is negative we would get a - sign printed. In the same way can we get + before the positive numbers.

int x=-1;
cout<<"x="<<x;

gives output x=-1

but,..

int x=+1;
cout<<"x="<<x;

gives output as x=1 but how do i get it printed as x=+1

I know we can take cases by using if-else for x>0 and x<0;..but without using the if-else is there any direct way of printing in c++

Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37

3 Answers3

13

Use std::showpos:

int x = 1;
std::cout << "x=" << std::showpos << x;
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

C++20 std::format option +

According to https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification the following should hold:

#include <format>

// "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);

The existing fmt library implements it for before it gets official support: https://github.com/fmtlib/fmt Install on Ubuntu 22.04:

sudo apt install libfmt-dev

Modify source to replace:

  • <format> with <fmt/core.h>
  • std::format to fmt::format

main.cpp

#include <iostream>

#include <fmt/core.h>

int main() {
    std::cout << fmt::format("{0:},{0:+},{0:-},{0: }\n", 1);
    std::cout << fmt::format("{0:},{0:+},{0:-},{0: }\n", -1);
}

and compile and run with:

g++ -std=c++11 -o main.out main.cpp -lfmt
./main.out

Output:

1,+1,1, 1
-1,-1,-1,-1

More information at: std::string formatting like sprintf

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
-1

How about:

cout<<"x="<<(x>0)?"+":""<<x;

it's a bit clumsy, but fits the bill

galets
  • 17,802
  • 19
  • 72
  • 101
  • Are you sure that this approach works? I got the following error `error: invalid operands of types ‘const char [1]’ and ‘int’ to binary ‘operator<<’` – Gilfoyle Oct 21 '19 at 13:57