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

5.7k views Asked by At

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!

3

There are 3 answers

7
Nate Kohl On BEST ANSWER

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?

0
MRAB On

Each line in the file consists of a name and a score separated by whitespace. You're reading each line but not splitting it into its parts (the name and the score).

2
Chris Hayden On

Ideally you would use a vector for this, but since it seems that you were asked to use arrays we'll stick with arrays. What you have above looks good until you start reading entries. A more idiomatic way to accomplish this is to use std::getline, i.e.

ifstream inFile( "winners.txt" );
std::string line;

while( std::getline( inFile, line )) {
  // Do work here.
}

Inside the loop you need to split the line on the space. Without solving the problem for you, I suggest you take a look at the find and substr functions of the string class: here. They will give you everything you need to solve the problem.