Printing Arrays

Hello all. I need some help with my program I have written below. Excuse any "poor" coding. Just started learning C++.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void displaySessions()
{
ifstream sessions;
sessions.open("sessions.txt");
if (sessions.is_open())
{
string sessionName[24];
int time[24];
int spacesLeft[24];

for (int i = 0; i < 24; i++)
{
sessions >> sessionName[i];
sessions >> time[i];
sessions >> spacesLeft[i];
cout << sessionName[i] << " " << time[i] << " " << spacesLeft[i] << endl;


}
sessions.close();
while (true);
}
else
{
cout << "Error, Could not read file." << endl;

}

}
int main()
{
displaySessions();

}

When I run this program, I get the following output.

Welcome 9 42
Metallurgy 10 12
Linguistics 10 1
Robotics 11 0
Robotics 12 5
Psychology 12 3
Tradecraft 11 5
Methodology 10 42
Oenology 10 12
Linguistics 14 6
Robotics 14 0
Robotics 15 16
Psychology 14 3
Tradecraft 13 5
Paleoludology 11 42
Metallurgy 11 12
Linguistics 10 6
Dramatics 15 0
Noology 14 42
Psychology 15 0
Tradecraft 16 19
Heuristics 12 2
Informatics 11 12
Linguistics 15 6

How do I write code to line up all of the numbers into two columns. Or is there a better way to achieve what I am trying to do??
Last edited on
For a beginner your code looks good and works well.
To format the output have a look at setw to set the field width - in <iomanip>
1
2
  cout.setf(ios::left);
  cout << setw(16) << sessionName[i] << " " << setw(5) << time[i] << " " << spacesLeft[i] << endl;


You need to play around with the numbers.
Topic archived. No new replies allowed.