JOHNSMITH8338 JOHNSMITH8338 - 3 months ago 11
C++ Question

How to align my displayed data to look like a table?

I am currently learning C++. I am to read in data from a file into the table below. I am able to read the data in but in the table it does not like this:


StdID A1 A2 A3




030302 9 5 6


but rather as


030302

9

5

6

etc.


How do I format this correctly into the table? I tried setw but it didn't solve the problem.

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main()
{
int StdID=0, A1=0, A2=0, A3=0;

ifstream fin;
fin.open("data.txt");
if(!fin)
cout << "The file does not exist.";
else{
cout << "Std-ID A1 A2 A3 Min Max Avg\n";
cout << " ---------------------------------------------------\n";
while (!fin.eof())
{
fin >> StdID >> A1 >> A2 >> A3;
cout << setw(10) << StdID << endl;
cout << setw(10) << A1 << endl;
cout << setw(10) << A2 << endl;
cout << setw(10) << A3 << endl;
}
}



return 0;
}

Answer

Each time you are displaying a variable, you are displaying a new line as well (by using each of the << endl;).

This should work:

while (!fin.eof())
  {
    fin >> StdID >> A1 >> A2 >> A3;
    cout << setw(10) << StdID << setw(10) << A1 << setw(10) << A2 << setw(10) << A3 << endl;

    // You may also break it down like this:
    //cout << setw(10) << StdID;
    //cout << setw(10) << A1;
    //cout << setw(10) << A2;
    //cout << setw(10) << A3 << endl; // one endl on each iteration
  }

Advice: You may need to learn Why is iostream::eof inside a loop condition considered wrong. Better use this condition instead:

while (fin >> StdID >> A1 >> A2 >> A3)

Edit:

The Tab key \t would still work with strings, similar way to this:

cout << "Std-ID\t\t\tA1\t\t\tA2\t\t\tA3\t\t\tMin\t\t\tMax\t\t\tAvg\n";

Also you better use if (fin.is_open()) to check if the file was opened successfully.