user8628552
user8628552

Reputation: 41

How to fill up a dynamic arrays using values stores in a text file

I had a text file which contains the number of students and courses, names of students and their respective grades for each courses. I wanted to access the names of the student from the text file and stored them in a dynamic array of strings. I tried using this but it only print out one name: what am I doing wrong. please help

string accessFile;
ifstream getFile;
string firstName;
string lastName;
string studentName;
string *names = NULL;
int rows;
getFile.open("chris.txt");
if (getFile.good()) {
    getline(getFile, accessFile);
    istringstream inFF(accessFile);
    inFF >> rows;
    names = new string[rows];
    while (getline(getFile, accessFile)) {
        istringstream inFF(accessFile);
        inFF >> firstName >> lastName;
        studentName = firstName + " " + lastName;
        for (int i = 0; i < rows; i++) {
            names[i] = studentName;
        }
        cout << rows << endl;
        for (int i = 0; i < rows; i++)
        {
            cout << names[i] << endl;
        }
        delete[] names;
    }

The text file info, is like this:

6 7 
Cody Coder 84 100 100 70 100 80 100 65 
Harry Houdini 77 68 65 100 96 100 86 100 
Harry Potter 100 100 95 91 100 70 71 72 
Mad Mulligun 88 96 100 90 93 100 100 100 
George Washington 100 72 100 76 82 71 82 98 
Abraham Lincoln 93 88 100 100 99 77 76 93

Upvotes: 0

Views: 63

Answers (1)

Sid S
Sid S

Reputation: 6125

You could do something like this:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    ifstream getFile;
    vector<string> names;
    getFile.open("chris.txt");
    if (getFile.good())
    {
        int rows;              // There are two numbers at the beginning of the data,
        getFile >> rows;       // the first one is number of rows.

        int whatsThis;         // The second one is not specified.
        getFile >> whatsThis;  // 

        while (rows--)
        {
            string firstName, lastName;
            getFile >> firstName >> lastName;
            names.push_back(firstName + ' ' + lastName);

            // Grades are not used, but must be read
            for (int i = 0; i < 8; i++)
            {
                int grade;
                getFile >> grade;
            }
        }
        for (auto name : names)
        {
            cout << name << endl;
        }
    }
    return 0;
}

Upvotes: 1

Related Questions