Print Leading Zeros With C++ Output Operator

Print leading zeros with C++ output operator?

This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question.

#include <iostream>
#include <iomanip>

using namespace std;
cout << setw(5) << setfill('0') << zipCode << endl;

// or use this if you don't like 'using namespace std;'
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;

The most common IO manipulators that control padding are:

  • std::setw(width) sets the width of the field.
  • std::setfill(fillchar) sets the fill character.
  • std::setiosflags(align) sets the alignment, where align is ios::left or ios::right.

And just on your preference for using <<, I'd strongly suggest you look into the fmt library (see https://github.com/fmtlib/fmt). This has been a great addition to our toolkit for formatting stuff and is much nicer than massively length stream pipelines, allowing you to do things like:

cout << fmt::format("{:05d}", zipCode);

And it's currently being targeted by LEWG toward C++20 as well, meaning it will hopefully be a base part of the language at that point (or almost certainly later if it doesn't quite sneak in).


(a) If you do need to handle negative numbers, you can use std::internal as follows:

cout << internal << setw(5) << setfill('0') << zipCode << endl;

This places the fill character between the sign and the magnitude.


(b) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)

Printing leading zeros in a number in C

The best way to have input under control is to read in a string and then parse/analyze the string as desired. If, for example, "exactly five digits" means: "exactly 5 digits (not less, not more), no other leading characters other than '0', and no negative numbers", then you could use function strtol, which tells you where number parsing has ended. Therefrom, you can derive how many digits the input actually has:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int main() {

char line[50];
if (fgets(line,50,stdin)) {
if (isdigit((unsigned char)line[0])) {
char* endptr = line;
long number = strtol(line, &endptr, 10);
int nrOfDigitsRead = (int)(endptr - line);
if (nrOfDigitsRead != 5) {
printf ("invalid number of digits, i.e. %d digits (but should be 5).\n", nrOfDigitsRead);
} else {
printf("number: %05lu\n", number);
}
}
else {
printf ("input does not start with a digit.\n");
}
}
}

Printing leading spaces and zeros in C/C++

To print leading space and zero you can use this :

int x = 119, width = 5;

// Leading Space
printf("%*d\n",width,x);

// Leading Zero
printf("%0*d\n",width,x);

So in your program just change this :

int i, digit, width=5, x=15;

if(x%2==0) // number even
printf("%*d\n",width,x);
else // number odd
printf("%0*d\n",width,x);

What directive can I give a stream to print leading zeros on a number in C++?

It's not as clean as I'd like, but you can change the "fill" character to a '0' to do the job:

your_stream << std::setw(2) << std::hex << std::setfill('0') << x;

Note, however, that the character you set for the fill is "sticky", so it'll stay '0' after doing this until you restore it to a space with something like your_stream << std::setfill(' ');.

How to add user defined variable leading zeros in C sprintf?

To make the width dynamic (not hard-coded in the format string), you write it like this:

sprintf(CNum,"%0*ld",blank,num); 

Instead of a hard-coded width 3 as in "%03ld", the asterisk indicates that the next argument (which must be of type int) is to be taken as the width.

how to store 0 in MSB of int datatype in C++?

First of all, you should get 65 as 0101 is parsed as octal 101 (64+1).


If you want to use binary literal, you can prepend 0b

#include<iostream>

using namespace std;

int main(){
int x = 0b0101;
cout<<x;
return 0;
}

https://godbolt.org/z/5Pxqehz7P

Stringifying with leading zeros

Very ugly but this should do the trick:

#include <stdio.h>

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#define VERSION 6

#if (version < 10)
#define DEVICE_NAME "MyDevice000" STR(VERSION)
#elif (version < 100)
#define DEVICE_NAME "MyDevice00" STR(VERSION)
#elif (version < 1000)
#define DEVICE_NAME "MyDevice0" STR(VERSION)
#else
#define DEVICE_NAME "MyDevice" STR(VERSION)
#endif

int main(void)
{
puts(DEVICE_NAME);
}

How to remove preceding '0' from numbers 10 and above?

std::cout <<"." << std::setfill('0') << std::setw(2) << a;

Print exponential notation with one leading zero with C++

As I said, what you ask is non-standard, but you can achieve that with a trick:

#include <iostream>
#include <iomanip>
#include <cmath>

class Double {
public:
Double(double x): value(x) {}
const double value;
};

std::ostream & operator<< (std::ostream & stream, const Double & x) {
// So that the log does not scream
if (x.value == 0.) {
stream << 0.0;
return stream;
}

int exponent = floor(log10(std::abs(x.value)));
double base = x.value / pow(10, exponent);

// Transform here
base /= 10;
exponent += 1;

stream << base << 'E' << exponent; // Change the format as needed

return stream;
}

int main() {
// Use it like this
std::cout << std::setprecision(6) << std::fixed;
std::cout << Double(-2.203e-15) << std::endl;
return 0;
}

The Double wrapper is needed because you cannot redefine << for double.

I did not test that way of separating exponent and base against the odds of floating point, maybe you can come up with a better alternative, but you get the idea :)



Related Topics



Leave a reply



Submit