I am writing a program that echos an input .txt file. The .txt file looks like this: (I put this in code format so that the spaces are shown)
1 2 3 4 5 6 7 8 9 10 11 12
Bailey M CC 68
Harrison F CC 71
Grant M UN 75
Peterson F UN 69
Hsu M UN 79
Bowles M CC 75
Anderson F UN 64
Nguyen F CC 68
Sharp F CC 75
Jones M UN 75
McMillan F UN 80
Gabriel F UN 62
When the .txt file is echoed all the white space is removed and it just doesn't read well at all. My program functions properly, but I would like to make it so that the white space stays consistent. How can I do this? I tried setw(5) ('5' for example...) but it still doesn't line up cleanly due to the different character counts in the various names.
You could keep track of the number of letters in the name, and then add the number of spaces you want based on the position you want minus the number of letters in the name, like spaces = 20 - name.size(), where 20 can be replaced with the number of spaces you want.
In addition to echoing the input file my program also must calculate the average scores for male and female test scores, community college and university test scores, and over all average test scores.
So in order to accomplish this I've established a loop that first reads the name and if a name is read, then it goes on to tally the other data and eventually outputs an average.
So the beginning of my loop reads like this:
1 2 3 4 5 6 7 8 9
while (inData >> name)
{
char sex;
int score;
string school;
inData >> sex >> school >> score;
cout << name << sex << school << score << endl;
And goes on to tally the rest of the information.
Those both seem look feasible suggestions, but I'm unsure how to incorporate this into my code as I have it now.
#include <iostream>
#include <string>
#include <fstream>
int main()
{
constchar* const path = "file.txt" ;
// create test file
{
std::ofstream(path) << R"(Bailey M CC 68
Harrison F CC 71
Grant M UN 75
Peterson F UN 69
Hsu M UN 79
Bowles M CC 75
Anderson F UN 64
Nguyen F CC 68
Sharp F CC 75
Jones M UN 75
McMillan F UN 80
Gabriel F UN 62
)" ;
}
// echo input file
{
std::cout << std::ifstream(path).rdbuf() ;
}
// read data, and print out what was read
{
std::cout << "\n-----------\n" ;
std::ifstream file(path) ;
std::string name ;
char sex ;
std::string school ;
int score ;
while( file >> name >> sex >> school >> score )
{
std::cout << "name: " << name << '\n'
<< "sex: " << sex << '\n'
<< "school: " << school << '\n'
<< "score: " << score << "\n\n" ;
}
}
}
Am I reading your response correctly in that you've provided the data from the input file manually? This program has to work with any .txt file using the same type of data. (example: just different names, scores, etc)