Cody
Cody

Reputation: 43

How do I show a positive/negative sign on everything but 0 when outputting to a stream?

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

Answers (3)

rishikesh tadaka
rishikesh tadaka

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

taocp
taocp

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

Scott Olson
Scott Olson

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

Related Questions