如何从C++文件中读取相乘字符数组
How to read multiply char arrays from a file in C++
文件"运动员信息.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++;
}
这将依赖于输入格式正确。
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?