【问题标题】:Forging multiple name lists from a text file into one将文本文件中的多个名称列表合并为一个
【发布时间】: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


    【解决方案1】:

    您正在阅读 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));
    

    【讨论】:

      猜你喜欢
      • 2019-11-04
      • 2013-01-09
      • 2021-11-08
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多