iostream equivalent of printf("% N.Me", arg);

When using printf to output data, you can use something like below to get the data to line up column-wise.

printf("% .5e", arg);

The above will print a number in scientific notation format, right justify, with 5 decimal points of precision. As an example,

printf("% .5e\n", 3.1);
printf("% .5e\n", -M_PI);

It may be hard to see, but there is a space between the % sign and the .(period).

displays:
3.10000e+00 // There is supposed to be a space in front of the 3, but the editor is removing extra spaces
-3.14159e+00 // In my test code, it displays the way it should.with the decimal columns lined up.
// An assumption is also being made that you are using a monospace font also.

Neat as you please.

I have tried several different ways to mimic this behavior using iostreams with no success. Is there a way to do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cmath>
using namespace std;

int main(int argc, char** argv)
{
	printf("using printf\n");
	printf("% .5e\n", M_PI);
	printf("% .5e\n", -M_PI);
	printf("decimal point columns line up\n");

	cout.precision(5);
	cout << "using streams" << endl;
	cout << scientific << M_PI << endl;
	cout << scientific << -M_PI << endl;
	cout << "decimal point columns do not line up" << endl;
	return 0;
}


using printf
 3.14159e+00
-3.14159e+00
decimal point columns line up
using streams
3.14159e+00
-3.14159e+00
decimal point columns do not line up


I should have posted these examples when I initially posted this to show the problem I am having.

http://ideone.com/o6ps6
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
   cout.precision(5);

   cout.setf(ios::scientific);
   cout << 3.1 << endl;

   //or
   cout << scientific << 3.1415926535 << endl;

   //note that the scientific flag is set until you
   //set it to something else (like fixed)
   cout << 5.2 << endl;
   cout << fixed << 6.32 << endl;

   return 0;
}


Output:

3.10000e+000
3.14159e+000
5.20000e+000
6.32000
Last edited on
Took me some time but I figured it out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <iomanip>
#include <cmath>

int main(int argc, char** argv)
{
	printf("using print\n");
	printf("% .5e\n", M_PI);
	printf("% .5e\n", -M_PI);

	cout << scientific << setprecision(5) << right;
	cout << setw(12) << M_PI << endl;
	cout << scientific << setprecision(5) << right;
	cout << setw(12) << -M_PI << endl;

	return 0;
}

using printf
 3.14159e+00
-3.14159e+00
using streams
 3.14159e+00
-3.14159e+00

Topic archived. No new replies allowed.