Question about Printf and Cout (Sorry, EN isn't my mother language so I couldn't make a clearly tittle)

Hi guys!

I'm having an issue like these below examples:

Example:
I have a variable: x = 1.2345 and I want to output "x = 1.23" to the screen.
Therefore, in C, I have this code
 
  printf("x = %.2f", x);


Another example:
x = 1; y = 2; z = 3;
I want to output "1 2 3" to the screen.
So I use this C code:
 
  printf("%4d %4d %4d", x, y, z);


So the question is: "Is "cout" in C++ able to do the same? Syntax?"

Many thanks!
(I'm so sorry if my English is bad, because it is not my mother language)
Last edited on
Yes, you can do the same thing with cout.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cstdio>
#include <iostream>
#include <iomanip>

int main()
{
	{
		double x = 1.2345;
		
		std::printf("x = %.2f\n", x);
		std::cout << "x = " << std::fixed << std::setprecision(2) << x << '\n';
	}
	
	{
		int x = 1;
		int y = 2;
		int z = 3;
		
		std::printf("%4d %4d %4d\n", x, y, z);
		std::cout << std::setw(4) << x << ' ' 
		          << std::setw(4) << y << ' ' 
		          << std::setw(4) << z << '\n';
	}
}

http://www.cplusplus.com/reference/ios/fixed/
http://www.cplusplus.com/reference/iomanip/setprecision/
http://www.cplusplus.com/reference/iomanip/setw/
Last edited on
Topic archived. No new replies allowed.