【发布时间】:2021-12-20 08:54:54
【问题描述】:
我需要从 txt 文件中获取姓名列表,然后按字母顺序对它们进行排序。 但让我们首先关注获取列表本身..
这是输入的txt文件(格式由练习给出) (cmets 是练习给出的解释,实际上并不存在)
3 // the number of total name groups
5 // the number of names in the individual group
Ambrus Anna
Bartok Hanna Boglar
Berkeczi Aron
Kovacs Zoltan David
Sukosd Mate
7
Biro Daniel
Csoregi Norbert
Drig Eduard
Dulf Henrietta
Fazekas Gergo
Gere Edit
Pandi Aliz
6
Albert Nagy Henrietta
Benedek Andor
Gere Andor
Lupas Monika
Pulbere David
Sallai Mark
所以,我正在尝试所有 3 个单独的名称组并将它们放在一个数组中.. 这是代码:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
void input(const char* fname, int& n, char students[100][100])
{
ifstream file(fname);
int groups, studNum;
char temp[50], emptyline[50];
file >> groups;
for(int i = 0; i < groups; i++)
{
file >> studNum;
file.getline(emptyline, 100); //I actually don't know why there is an empty line after the numbers
for(int j = 0; j <= studNum; j++)
{
//I'm going line by line with getline.. I'm not using fin, because sometimes the name consists of 3 elements, sometimes of 2
file.getline(temp, 100);
strcat(students[j + n], temp);
}
n += studNum;
}
file.close();
}
int main()
{
int n = 0;
char students[100][100];
input("aigi4153_L2_6.txt", n, students);
//printing the array
for(int i = 0; i < n; i++)
{
cout << students [i] << endl;
}
return 0;
}
所以,代码看起来不错,而且几乎可以运行。输出是 99%,但是在“Pulbere David”这个名字之前有一个神秘的“6”。我有不知道那是怎么回事..我认为它与“Albert Nagy Henrietta”之前的“6”没有任何关系,因为例如,如果我将其更改为“7”,那么神秘的“6”将仍然是一样的号码。。 所以,输出是这样的:
Ambrus Anna
Bartok Hanna Boglar
Berkeczi Aron
Kovacs Zoltan David
Sukosd Mate
Biro Daniel
Csoregi Norbert
Drig Eduard
Dulf Henrietta
Fazekas Gergo
Gere Edit
Pandi Aliz
Albert Nagy Henrietta
Benedek Andor
Gere Andor
Lupas Monika
6Pulbere David //here is the "mysterious 6"
Sallai Mark
关于这 6 个如何到达那里的任何想法?
【问题讨论】:
标签: c++ string ifstream getline