如何使用值存储在文本文件中填充动态数组

时间:2018-01-14 20:50:56

标签: c++

我有一个文本文件,其中包含学生和课程的数量,学生的姓名以及每门课程的各自成绩。我想从文本文件中访问学生的名字,并将它们存储在一个动态的字符串数组中。我尝试使用它,但它只打印出一个名称: 我究竟做错了什么。请帮忙

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;
    }

文本文件信息如下:

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

1 个答案:

答案 0 :(得分:1)

你可以这样做:

#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;
}