c++ - 如何使用数组 (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;
}
解决方案
您可以使用std::vector
object 而不是常规数组。它看起来像这样:
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++)
推荐阅读
- php - PHP Notice: Unknown: 在系统临时目录中创建的文件 Unknown on line 0
- javascript - 在其他类节点js中调用类的方法而不使用NEW关键字
- javascript - 如何将项目附加到存储在文件中的 JSON?
- arrays - 返回找到相邻的重复数字对所需的最少乘法次数
- java - 如何在 mongodb java 驱动程序中使用编解码器设置 ClusterSettings 的 URI
- python - 如何将 JSON 内容传递到另一个 JSON 文件
- python - 将一个数据帧中一行的值设置为另一个数据帧的一行中包含的值
- android - 如何解决 Flutter 调试问题?(Unix,Ubuntu)
- vue.js - 如何将组件对象放入合成 API 中的全局窗口变量中?
- python - 尽管相同参数的数量不同,但结果相同