I am having trouble with reading in information from a .txt file using ifstream. The text file contains:
KNIFE JACK
1.3 6.0 5.1 6.3 5.9 6.5
WILLIAMSON FLIP A
1.4 3.5 4.1 4.7 7.2 3.8
SOMMER TODD
1.2 8.0 9.1 8.1 9.3 9.0
SWAN MIKE
1.1 4.3 2.1 9.9 6.2 7.0
How can I get the program to read in "WILLIAMSON FLIP A" and continue reading the rest?
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const int JUDGES = 5;
struct Info
{
string name;
double difficultyFactor;
double score[5];
};
void collectData(Info *, Info *, Info *);
int main()
{
Info diver1, diver2, diver3; //Names of data type Info
collectData(& diver1, & diver2, & diver3);
cout << "Show data for the divers:\n";
cout << diver1.name << " " << diver1.difficultyFactor << " ";
for (int i = 0; i < JUDGES; i++)
{
cout << setprecision(1) << fixed;
cout << diver1.score[i] << " ";
}
/*cout << endl << diver2.name << " " << diver2.difficultyFactor << " ";
for (int i = 0; i < JUDGES; i++)
{
cout << setprecision(1) << fixed;
cout << diver2.score[i] << " ";
}
cout << endl << diver3.name << " " << diver3.difficultyFactor << " ";
for (int i = 0; i < JUDGES; i++)
{
cout << setprecision(1) << fixed;
cout << diver3.score[i] << " ";
}*/
}
void collectData(Info * diver1, Info * diver2, Info * diver3)
{
char temp;
ifstream inputFile;
inputFile.open("DIV1.txt");
getline(inputFile, diver1->name); //Info for 1st diver
inputFile >> diver1->difficultyFactor;
for (int i = 0; i < JUDGES; i++)
{
inputFile >> diver1->score[i];
}
getline(inputFile, diver2->name); //Unable to read in the name
cout << "----" << diver2->name << "++";
inputFile >> diver2->difficultyFactor;
cout << "&&" << diver2->difficultyFactor << "^^";
/*for (int i = 0; i < JUDGES; i++)
{
inputFile >> diver2->score[i];
}
getline(inputFile, diver3->name); //Info for 3rd diver
inputFile >> diver3->difficultyFactor;
for (int i = 0; i < JUDGES; i++)
{
inputFile >> diver3->score[i];
}*/
}
This is what the program output is:
----++&&0^^Show data for the divers:
KNIFE JACK 1.3 6.0 5.1 6.3 5.9 6.5 Program ended with exit code: 0
I would love to help but I do not want to read the code without the [ code ] [ /code ] tags. You put the first one at the start of your code and the 2nd one at the end of it
The problem you're having it due to the mix of operator>> with getline.
When you've finished extracting the scores there's still a new line char left on the current line so the call to getline returns the rest of the current line (which is an empty string) rather than the name on the following line.
If you call istream::ignore() after you've done reading the scores, to ignore the rest of the current line, then getline should read the line you expect.
lazy form
inputFile.ignore(1024, '\n'); // ignore up to 1024 chars or the next \n