For whatever reason, you can't open lab2.txt so the open() at line 10 fails.
This gets you to the while loop at line 13.
You enter a valid file name.
The loop at line 27 runs. By the way, lines 30-38 have no effect. For each line, the very next line blows away the assignment.
Eventually you read all the data at line 27 and
the next extraction at line 27 fails.
So now fin.fail() is true.
You close the file at line 47. fin.fail() is still true.
The loop at line 13 executes again. fin.fail() is still true so around you go.
Did you mean to have line 25 inside the loop at line 13? The indentation suggests not. Here is your code with the indentation reflecting the actual block structure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
struct Student {
string name;
double score;
};
int
main()
{
ifstream fin;
string userfile;
string str;
double a1, a2, a3, a4, a5, a6, a7, a8, a9, a10;
vector < Student > student;
Student stu;
fin.open("lab2.txt");
if (fin.fail()) {
while (fin.fail()) {
cout << "Input file failed to open.\n";
cout << "\nPlease enter a file name/path ";
cin >> userfile;
cout << endl;
cout << "You entered \"" << userfile << "\"\n";
fin.open(userfile.c_str());
if (fin) {
cout << "input file is valid\n";
while (fin >> str >> a1 >> a2 >> a3 >> a4 >> a5 >> a6 >> a7 >> a8 >> a9 >>
a10) {
stu.name = str;
stu.score = a1;
stu.score = a2;
stu.score = a3;
stu.score = a4;
stu.score = a5;
stu.score = a6;
stu.score = a7;
stu.score = a8;
stu.score = a9;
stu.score = a10;
student.push_back(stu);
}
}
cout << "before close fail is " << fin.fail() << '\n';
fin.close();
cout << "after close fail is " << fin.fail() << '\n';
}
//fin.open (userfile);
}
if (fin) {
while (fin >> str >> a1 >> a2 >> a3 >> a4 >> a5 >> a6 >> a7 >> a8 >> a9 >> a10) {
stu.name = str;
stu.score = a1;
stu.score = a2;
stu.score = a3;
stu.score = a4;
stu.score = a5;
stu.score = a6;
stu.score = a7;
stu.score = a8;
stu.score = a9;
stu.score = a10;
student.push_back(stu);
}
}
fin.close();
return 0;
}
|
You shouldn't repeat the code that reads the data. Write a block of code that loops to get the name of an existing file. When you exit that loop, run the loop to extract the data.