Search code examples
c++filefstreamsstream

Extracting lines from .txt file, then store words into separate arrays | C++


Our professor gave us this assignment, where we have a .txt file with the following format:

John 23
Mary 56
Kyle 99
Gary 100
...etc. etc.

What we have to do is read the file, and store the names and scores in parallel arrays.

This is turning out to be a bit more challenging to me than I anticipated. What is confusing me, when searching around stack, is all the different libraries people use to do this. Our Prof just wants us to use string, fstream, and sstream to do this.

Below is what I've come up with so far, it compiles perfectly, splits the scores from the names but stores them in the same array:

#include <string>
#include <sstream>
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  const int SIZE = 50;
  string names[SIZE];
  int score [SIZE];
  short loop = 0;
  string line;

  ifstream inFile("winners.txt");

  if (inFile.is_open())
  {
    while(!inFile.eof())
    {
       istream& getline(inFile >> line);
       names[loop] = line;
       cout << names[loop] << endl;
       loop++;
    }
    inFile.close();
  }

  else cout << "Can't open the file" << endl;

  return 0;
}

I'm not looking for someone to solve my HW problem, I just want a push in the right direction!


Solution

  • If you want to read two things for each line of input, it seems reasonable to have two "read" statements:

    std::string name;
    inFile >> name;
    
    int score;
    inFile >> score;
    
    std::cout << "Read score " << score << " for name " << name << '\n';
    

    ...then you can do that repeatedly until you've read the entire file.


    Edit: After you get the basic logic worked out, you might want to think about error handling. For example, what is appropriate behavior for your program if the input file doesn't contain 50 pairs of (name, score)? How can you change your code to get that behavior?