首页 > 解决方案 > 如何使用数组 (C++) 读取具有未定义数量值的 .txt 文件?

问题描述

我对编程完全陌生,所以如果我不能很好地解释这一点,我很抱歉。对于我的 C++ 作业,我必须编写一个面向对象的程序,该程序从文本文件中读取名称(文本文件只是名字的列表),并使用数组按字母顺序将它们打印到控制台。最初,任务的描述说该文件有 20 个名称,所以我的代码基于此。该程序可以工作,但现在发现分配描述不准确,我们不应该假设文本文件具有特定数量的名称。如何将我的代码从专门读取 20 个名称转换为读取未定义数量的名称,同时仍使用数组?我不完全理解我正在实施的概念,所以它' 我很难知道如何在仍然遵循作业要求的同时更改我的代码。这是我的代码:

#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>

using namespace std;


class Names
{
private:
    ifstream inStudents;
    string studentNames[20];
    string name; 
    int j; 

public:
    Names();
    ~Names();
    void openFile(string);
    void testFile();
    void readFile();
    void sortNames();
    void closeFile();
    void display();
};

Names::Names()
{

}
Names::~Names()
{

}
void Names::openFile(string d) 
{
    inStudents.open(d); 

}

void Names::testFile()
{
    if (!inStudents)
    {
        cout << "File did not open" << endl;
        exit(10);
    }
}

void Names::readFile()
{
    cout << "Reading the input file..." << endl; 
    int j = 0; 
    while (inStudents >> name && j < 20)
    {
        studentNames[j++] = name;
    }
}

void Names::sortNames() 
{ 
    sort(studentNames, studentNames + 20);
}

void Names::closeFile()
{
    inStudents.close();
}

void Names::display() 
{ 
    cout << endl << "The alphabetical list: " << endl << endl;
    for (int i = 0; i<20; i++)
        cout << studentNames[i] << " " << endl;
    cout << endl << endl;
}

int main() 
{
    Names r;
    r.openFile("students.txt");
    r.readFile();
    r.testFile();
    r.sortNames();
    r.display();
    r.closeFile();

    return 0;
}

标签: c++

解决方案


您可以使用std::vectorobject 而不是常规数组。它看起来像这样:

vector<string> studentNames;

现在,不要使用以下行将名称插入到数组中的已知位置:

studentNames[j++] = name;

利用:

studentNames.push_back(name);
//or
studentNames.emplace_back(name);

函数内的while循环readFile将如下所示:

while (inStudents >> name)
{
    studentNames.push_back(name);
}

要现在显示它,您只需在display函数中更改范围即可。该vector对象包含一个名为的函数,该函数size返回您当前的vector大小,或者换句话说 - 包含的元素计数vector。它看起来像以下行:

for (int i = 0; i < studentNames.size(); i++)

推荐阅读