JOHNSMITH8338 JOHNSMITH8338 - 1 year ago 63
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






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;"data.txt");
cout << "The file does not exist.";
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 Source

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)


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download