C++ 如何使用数组(C+;+;)读取具有未定义数量的值的.txt文件?
我对编程一无所知,所以如果我不能很好地解释这一点,我很抱歉。对于我的C++赋值,我必须编写一个面向对象程序,它从文本文件中读取名称(文本文件只是一个名字的列表),并用数组按字母顺序将它们打印到控制台。最初,作业的描述说文件有20个名称,所以我的代码就是围绕这个名称编写的。程序可以运行,但现在发现赋值描述不准确,我们不应该假设文本文件有特定数量的名称。如何在仍然使用数组的情况下,将代码从专门读取20个名称转换为读取未定义数量的名称? 我不完全理解我正在实现的概念,因此我很难知道如何在仍然遵循任务要求的情况下更改代码。这是我的密码:C++ 如何使用数组(C+;+;)读取具有未定义数量的值的.txt文件?,c++,C++,我对编程一无所知,所以如果我不能很好地解释这一点,我很抱歉。对于我的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;
类名
{
私人:
ifstream仪器;
字符串studentNames[20];
字符串名;
int j;
公众:
名称();
~Names();
void openFile(字符串);
void testFile();
void readFile();
void sortNames();
void closeFile();
void display();
};
名称::名称()
{
}
姓名::~Names()
{
}
void name::openFile(字符串d)
{
开放式(d);
}
void name::testFile()
{
如果(!仪表)
{
cout您可以使用std::vector
对象而不是常规数组。它将如下所示:
vector<string> studentNames;
使用:
readFile
函数中的while
循环如下所示:
while (inStudents >> name)
{
studentNames.push_back(name);
}
要立即显示它,您只需在display
函数中更改范围。vector
对象包含一个名为size
的函数,该函数返回当前vector
大小,或者换言之,vector
包含的元素计数。它类似于下面的行:
for (int i = 0; i < studentNames.size(); i++)
for(int i=0;i
如果作业允许,请替换字符串studentNames[20]
与vector学生名;
和。像这样的作业可能不允许使用std::vector
,因为他们想让你知道如何编写自己的。如果是这样的话,你可以在堆栈溢出中搜索那些不得不编写自己的vector
的人提出的问题,以获得如何编写自己的vector
的建议推荐的阅读:C++中的数组必须在定义时声明其长度。因此,您的选择是有一个非常大的数组大小,可能在全局空间中(没有在函数内部声明)。如果超出限制,则使用硬停止来跟踪读取的条目数,或者按照建议,使用std::vector
,该工具专为此类对象而设计,并且易于排序。但该赋值听起来像是在指导您使用数组。
while (inStudents >> name)
{
studentNames.push_back(name);
}
for (int i = 0; i < studentNames.size(); i++)