将文本文件中的多个名称列表伪造为一个

Forging multiple name lists from a text file into one

我需要从 txt 文件 中获取姓名列表,然后按字母顺序对它们进行排序。 但是让我们首先关注获取列表本身..

这是输入的txt文件(练习给的格式) (评论是练习给出的解释,实际上并不存在)

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 个是如何到达那里的任何想法?

你正在阅读 6 作为名字的一部分,你最里面的循环应该是:

for(int j = 0; j < studNum; j++)

而不是

for(int j = 0; j <= studNum; j++)

此外,您永远不会初始化 students 数组的内容,因此 strcat 将尝试将名称附加到可能包含任何内容的字符串中。您应该将内容归零:

char students[100][100];
memset(students, 0, sizeof(students));