Reputation: 43
I would like to output my numbers in one of three following formats:
-1 0 +1
but the stream flag showpos
only allows
-1 +0 +1
Are there any easy shortcuts around this?
Upvotes: 4
Views: 8781
Reputation: 483
According to my understanding of your question. The following code may be useful for you. please correct if there is any mistakes.
// modify showpos flag
#include <iostream> // std::cout, std::showpos, std::noshowpos
int main () {
int p = 1;
int z = 0;
int n = -1;
std::cout << std::showpos << p << '\t' << z << '\t' << n << '\n';
std::cout << std::noshowpos << p << '\t' << z << '\t' << n << '\n';
return 0;
}
output
+1 +0 -1
1 0 -1
Upvotes: 1
Reputation: 23654
A brute force (ugly in a sense) way:
ofstream outFile.open("data.txt");
if (num ==0 ){
outFile<<num;
}
else
{
outFile << std::showpos << num ;
}
Upvotes: 1
Reputation: 3542
Just use an if statement to check if the value is 0 or not. If it is, print zero, otherwise print as you were with showpos.
I don't believe there is a shortcut for this, but the above is pretty easy.
Sample code
if(n == 0) {
cout << '0';
} else {
cout << showpos << n;
}
Upvotes: 4