Hi, I'm having trouble with an assignment. I have to open a text file like this that sorts the highest GPAS and Names
Joshua 3.1
Margaret 4.0
Jared 2.7
It sorts them from highest GPA to last with their names. We have to use two arrays. One for the names and one for the GPAS. I'm having trouble reading from the file and then adding the GPAS to one array and the Names to another. Help would be very much appreciated!
int i = 0;
std::ifstream fin("filename.txt");
while ( !fin.eof() )
{
fin >> array1[i]; // Read item A,
fin >> array2[i]; // Read B
// If they are like this: "John 8.5" it will put John in array1, and 8.5 in array2
++i;
}
#include <string>
#include <fstream>
#include <iostream>
using std::ifstream;
using std::cout;
using std::endl;
using std::cin;
int main()
{
constint size = 3;
std::string names[size];
float gpas[size];
int i = 0;
ifstream fin("filename.txt");
while ( !fin.eof() && (i < size))
{
fin >> names[i];
fin >> gpas[i];
++i;
}
for (int i = 0; i < size; ++i)
cout << names[i] << ": " << gpas[i] << endl;
return 0;
}
wolfgangs code works perfect for me. i am using codeblocks on windows 7. the only thing i noticed while playing was if the file isnt in the right spot the values are filled with junk. other then that with the proper file it works great.