Need help aligning text!

Hi guys, I am doing a small currency converter for my mini project and I have to use fstream. Currently I'm at the first part only. But anyway, after I run the program, I realised that the text are not aligned like what it is in the txt file. Therefore I need some help to align it :O. Thanks!! :D



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

using namespace std;

int main()
{
   ifstream infile;
   infile.open("Currencies.txt");
   string a, b, c;
   if (infile.is_open())
   {

   while (infile >> a >> b >> c)
   {
    cout<< a << " " << b << " " << c << " " <<endl;

   }

   }
   infile.close();

    return 0;
}
Last edited on
The simple solution is to just use a conservative setw():

cout << setw(10) << a << setw(10) << b << setw(10) << c << "\n";

That assumes that all strings (or whatever you are formatting) are 9 characters or less.


The more comprehensive solution is not friendly.

For each column, you must run through all the possible values and remember the width of the widest one.

Then you can print them out using setw(width[col]+1) for each column.

cout << setw(max_a+1) << a << setw(max_b+1) << b << setw(max_c+1) << c << "\n";

Hope this helps.
It works! Thank you :D
Topic archived. No new replies allowed.