String format

hy..i have a question about how to format the text in a console application.using printf();
for example if i wanted to write like this(let's say the that is the console).
i read about it somewhere in a book but i forgot it,and it is helpful.TY
1
2
3
4
  Hello
    My friend
     How can i do this ?
 ???????????????????????????
Are you trying to indent your output?
sry..i am not sure about what do you mean by indent..but i want to make a message to be at a specific length from the left side.for example..it is something like this but i can't remember exactly
printf(%4.....);
there´s an os specific way (saw it somewhere), but if its just for a few lines you could also just use:
cout<<" Hello".. So basically just enter the amount of spaces you want..

edit: @ programmer47: yes mihay wants to indent the input :)
Last edited on
Why printf() rather than std::cout? Using printf() for C++ apps is a bad habit to get into as a beginner.
I think this is what you're looking for: http://www.cplusplus.com/reference/iostream/manipulators/setw/
Although I agree with filipe and think that will probably work with what you are looking for, you always have the option of writing a function to do what you require (in this case it would be easy) as well.
ok..i found what i was looking for..finally.
printf("%3s","Hello"); // 3 spaces to the right
Thank you for the help..about the thing,that using cout is better,i don't now.First of all i am a beginner in C, C++ is something i will learn this year.But i started to read something about it and from what i saw there are some advantages,but there are some disadvantages too.

For example i now it is easier to write:cout << x;
Than printf("%d",x); // or %f,%s,what x is

But is some situations it is a bit too long,or complicate at first site to write something simple like:
printf("tab[%d]= ",i); // for an arry

With cout looks like this:
cout <<" tab[ "<< i <<" ]= ";

And also if you want to print a variable with a certain precision: float x=1.123456
printf("%.3f",x);// the result is 1.123
How can you do that with cout?

Now this is my opinion with the limited things i now about C++..so i maybe wrong..there must be something better with cout and cin , otherwise they would not have invented it :)
Last edited on
For the precision, #include<iomanip>:
cout << fixed << setprecision(3) << x;

As for the indentation, you might want to use:
cout << right << setw(8) << "Hello";

edit: "right" is of course the default setting so you don´t really need to write it, but it would work the analog way for the left indentation as well.
Last edited on
Topic archived. No new replies allowed.