Question

I am writing a program to write a head for a specific image format. This image format requires 256 characters as its header before any following raw image data. But I have problem padding empty spaces to make the header 256 characters long.

Below is an abstraction of my problem:

char pad[256];
sprintf( pad, "header info:%s=%f", "scale", 2.3);
cout<<pad<<"data here"<<endl;

The output is:

header info:scale=2.300000data here

However, the result I expect is like:

header info:scale=2.300000                            data here

where "data here" appears after 256 characters from the beginning of the file. How can I change the program to pad empty spaces in the character array?

Was it helpful?

Solution

Do this:

cout << setw(256) << left << pad << "data here" <<endl;

You may need #include <iomanip>.

BTW in your "real code" you should use snprintf to ensure there is no chance of a buffer overflow, assuming that your %s is going to get some argument that's worked out at runtime . (Or preferably replace the sprintf with a stringstream).

OTHER TIPS

Maybe this can help you. The format - which left aligns the text. For example, the following will left align the float text with a fixed width of 20. The default space character is used as padding.

sprintf( pad, "header info:%s=%-20f", "scale", 2.3);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top