Accept an integer and print the number along with its sign.
Accept an integer as a input
Print the number along with its sign.
10^-15 <= N <= 10^15
showpos
, a stream manipulator that automatically displays a +
sign for positive numbers without using any conditionals.
showpos
? ▼
showpos
is a stream manipulator in C++.
<iostream>
header+
sign when printedcout
, cerr
, clog
, or any ostream
Example:
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = -3;
cout << showpos; // Enable + for positive numbers
cout << a << " " << b << endl; // Output: +5 -3
}
showpos
Behavior ▼
Without showpos (normal behavior):
int x = 10;
int y = -7;
cout << x << " " << y << endl;
// Output: 10 -7
Notice positive numbers don't get a +
by default.
With showpos:
cout << showpos;
cout << x << " " << y << endl;
// Output: +10 -7
✅ Automatically prints +
for positive numbers and -
for negatives.
A. Permanent for the stream
Once you do cout << showpos;
, all subsequent numbers in that stream will have the +
for positives, until you reset it.
cout << showpos;
cout << 3 << endl; // +3
cout << -4 << endl; // -4
cout << 0 << endl; // +0
B. Temporary for a single print
You can combine it in a single cout statement:
cout << showpos << 7 << endl; // +7
C. Disabling showpos
If you later want to stop showing +
for positives:
cout << noshowpos;
cout << 5 << endl; // 5
So showpos
/ noshowpos
are like on/off switches for the stream.
showpos
is purely formatting – the stream handles printing internally.
Your code doesn't need if (n >= 0)
to add a +
.
Therefore: This is perfect for questions that explicitly forbid conditions!
if
statements? :
+
, negatives have -
showpos
→ adds +
automatically for positivesnoshowpos
→ disables it againsetw
, setfill
, etc.)#include <iostream>
using namespace std;
int main() {
int a;
cin >> a;
cout << showpos << a;
return 0;
}