Reading from a text file(strings and numbers)

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!
I'm just asking how will I read one line from the text file, extract the number and name separately and add them to the appropriate array.
1
2
3
4
5
6
7
8
9
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;
}
Last edited on
The words in the text file are is:

Joshua 3.1
Margaret 4.0
Jared 2.7

What you showed me doesn't work =/. I don't think its reading them separately.

Works fine for me.
GCC MinGW on Windows Custom Build;
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
#include <string>
#include <fstream>
#include <iostream>

using std::ifstream;
using std::cout;
using std::endl;
using std::cin;

int main()
{
  const int 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;
}
It opens the file for me and then the cursor just blinks infinitely.
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.
Topic archived. No new replies allowed.