如何从C++文件中读取相乘字符数组

How to read multiply char arrays from a file in C++

本文关键字:字符 数组 读取 C++ 文件      更新时间:2023-10-16

文件"运动员信息.txt"如下所示:

Peter Gab 2653 Kenya 127
Usain Bolt 6534 Jamaica 128
Bla Bla 2973 Bangladesh -1
Some Name 5182 India 129

我希望我的代码要做的是读取第一个字符串并将其分配给firstName数组(例如 Peter 存储在firstName[0]中),读取第二个字符串并将其分配给数组lastName(例如 Gab 存储在lastName[0]中)等等。我尝试了许多不同的方法,甚至尝试将其全部设置为字符串数组,但它不起作用。如果有人能告诉我代码中出了什么问题或如何去做,那就太好了!

提前感谢!

void readInputFromFile()
{
ifstream inputData;
inputData.open("Athlete info.txt");
const int SIZE=50;
char firstName[SIZE],
lastName[SIZE],
athleteNumber[SIZE],
country[SIZE];
int  athleteTime[SIZE];
int numOfCharacters=0;
if (inputData.is_open())
{
int i=0;
while(!inputData.eof())
{
inputData >> firstName[i]; 
inputData >> lastName[i]; 
inputData >> athleteNumber[i];
inputData >> country[i]; 
inputData >> athleteTime[i];
i++;
numOfCharacters++;
}
for (int i=0; i < numOfCharacters; i++ )
{
cout << "First Name: " << firstName[i];
cout << "Last name: " << lastName[i];
cout << "AthleteNumber: " << athleteNumber[i];
cout << "Country: " << country[i];
cout << "Time taken: " << athleteTime[i];
cout << endl;
}
}
else
{
cout << "ERROR" << endl;
}
inputData.close();
}

首先,你使用的是 c++,所以让我们使用 std::string,并使用类。让我们创建包含运动员所需的一切的运动员结构:

struct Athlete {
Athlete() = default;
Athlete(std::stringstream &stream) {
stream >> firstName 
>> lastName 
>> athleteNumber 
>> country 
>> athleteTime;
}
// every Athlete is unique, copying should be prohibited
Athlete(const Athlete&) = delete;
std::string firstName;
std::string lastName;
std::string athleteNumber;
std::string country;
std::string athleteTime;
}

也许你可以在这个上面多做一点工作,更好地封装它。

现在我们将使用 std::vector 来存储运动员,每次我们push_back时,我们都会调用 Athelete 构造函数,并从输入文件中读取行。稍后,您可以使用基于范围的 for 循环来访问矢量中的每个运动员。另请注意,ifstream 不会手动关闭,一旦对象超出范围,它就会自动关闭。

void readInputFromFile() {
ifstream inputData("Athlete info.txt");
std::vector<Athlete> athletes;
std::string line;
std::stringstream ss;
if (inputData.is_open() {
while (getline(inputData, line)) {
ss.str(line);
// directly construct in-place
athletes.emplace_back(ss);
}
for (const Athlete& a : athletes) {
/* ...*/
}
} else {
std:cerr << "ERROR" << std::endl;
}
}

最简单的更改是

while(inputData >> firstName[i])
{
inputData >> lastName[i]; 
inputData >> athleteNumber[i];
inputData >> country[i]; 
inputData >> athleteTime[i];
i++;
numOfCharacters++;
}

这将依赖于输入格式正确。