【问题标题】:Sorting structured data from txt对txt中的结构化数据进行排序
【发布时间】:2015-03-08 08:49:35
【问题描述】:

我的问题是对从 txt 文件中提取的一些数字进行排序。 当我编译文件时,程序停止工作。

    #include <stdio.h>
    #include <stdlib.h>



    struct student_grades{
    int number;
    char name[10];
    char surname[10];
    int grade;
    };

    typedef struct student_grades stgrade;


    void bubble_sort(int list[], int n){ //Line 16
  long c, d, t;

  for (c = 0 ; c < ( n - 1 ); c++)
  {
    for (d = 0 ; d < n - c - 1; d++)
    {
      if (list[d] > list[d+1])
      {
        /* Swapping */

        t         = list[d];
        list[d]   = list[d+1];
        list[d+1] = t;
      }
    }
  }
}


int main()
{
    int i=0;
    FILE *stu;  // file tipinde değişken tutacak
    FILE *stub;
    stu= fopen("student.txt","r");
    stub= fopen("stu_order.txt","a");


    stgrade stg[12];
        if(stu!=NULL){
        while(!feof(stu))
        {
            fscanf(stu,"%d",&stg[i].number);
            fscanf(stu,"%s",stg[i].name);
            fscanf(stu,"%s",stg[i].surname);
            fscanf(stu,"%d",&stg[i].grade);
            //fprintf(stub,"%d  %s  %s  %d\n",stg[i].number,stg[i].name,stg[i].surname,stg[i].grade);

               ++i;
        }
        bubble_sort(stg->number,12);    //Line 59

        fprintf(stub,"%d  %s  %s  %d\n",stg[1].number,stg[1].name,stg[1].surname,stg[1].grade); //control that is bubble  success?  

    }
    else
      printf("File Not Found");

    fclose(stu);
    fclose(stub);
    return 0;  

一开始我写了第 59 行

bubble_sort(stg.number,12);    

像这样。但它会出错并且无法编译。我用

改变它
bubble_sort(stg->number,12);    

它已编译但停止工作并收到警告

格式化输出:
在函数'main'中:
59 3 [警告] 传递 'bubble_sort' 的参数 1 使指针从整数而不进行强制转换 [默认启用]
16 6 [注意] 预期为 'int *' 但参数的类型为 'int'

学生.txt

80701056 Sabri Demirel 45  
52801022 Burak Erkin 68  
13801045 Umut Korkmaz 88  
74801334 Semih Potuk 58  
15678544 Enes Sezer 76  
42125884 Ahmet Can 84  
12355488 Emre Ozdemir 47  
18744125 Ugur Yildiz 64  
62184111 Mustafa Ozturk 80  
18412548 Ugur Akkafa 72  
94541771 Hakan Aktas 92  
36945245 Fatih Yagci 98  

【问题讨论】:

  • 您的bubble_sort 函数将对int 数组进行排序,但您想对struct student_grades 数组进行排序。这是不可能的。您必须创建一个可以对struct student_grades 数组进行排序的冒泡排序函数。请注意,交换会有点困难,因为您必须交换结构。
  • 在修复此代码中的大量其他错误的同时,也可以修复此问题:while (!feof(stu))
  • @WhozCraig 我想你明白了。操作:while(!feof(stu)) { fscanf(stu,"%d",&amp;stg[i].number); ... fscanf(stu,"%d",&amp;stg[i].grade); --> while (4 == fscanf(stu,"%d%9s%9s%d",&amp;stg[i].number,stg[i].name,stg[i].surname,&amp;stg[i].grade)) {

标签: c arrays sorting structure


【解决方案1】:

这是基于您的文件和结构 stgrade dand 的代码,它使用复杂度等于 O(log(n))qsort 函数)的快速排序,而不是库 stdlib.h 中的冒泡排序,并且生成所需的输出

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> //qsort function

struct student_grades{
    int number;
    char name[10];
    char surname[10];
    int grade;
};

typedef struct student_grades stgrade;

// the compare function is used by the qsort function to sort the structures 
// according to the grades values
int compare(const void* a, const void* b) 
{
return (*(stgrade *)a).grade - (*(stgrade *)b).grade;   
}

int main(int argc, char *argv[])
{
    FILE *stub, *stu;
    stu= fopen("student.txt","r");
    stub= fopen("stu_order.txt","a");

    stgrade tab[12]; // array that will contain the structures from student.txt file
    int i=0;
    for (i=0;i<12;i++)
    {
       // put the structures on the array
        fscanf(stu,"%d %s %s %d",&tab[i].number,tab[i].name,tab[i].surname,&tab[i].grade);
    }
      // use the qsort function that will sort the structures
    qsort(tab,12,sizeof(stgrade),compare);

    //loop to write the result on the output file
    for (i=0;i<12;i++)
    {
         // the write will be via the function fprintf 
        fprintf(stub,"%d %s %s %d\n",tab[i].number,tab[i].name,tab[i].surname,tab[i].grade);
    }

   // Check the output file :)

    return 0;
}

可以通过检查打开的文件来改进代码!!

【讨论】:

  • 非常感谢!我知道我的流程不适合冒泡排序,我们使用快速排序而不是冒泡排序。并且您使用 for 循环而不是 while。我的老师说使用 !feof() 可以防止错误。但是如果我们使用静态数组就没有问题了。再次感谢 :) 在土耳其语中我们说“Eyvallah”:)
  • 不要在下一个程序中使用while(!feof(file)),这就是link 的原因!!不客气!
  • 有趣的老师说使用!feof()可以防止错误。老师错了。检查像 fscanf() 这样的 IO 函数的结果是一个更好的解决方案。
  • 我认为他说动态数组是因为它可以扫描缓冲区中的一些文件。
  • 如果您不知道文件中有多少行,这将是一个很好的解决问题!首先你可以做一个循环来计算你有多少行,然后为动态数组分配所需的内存!那么您需要再次指向文件的开头并执行与上述答案相同的操作!
【解决方案2】:

嗯,你的编译器的输出告诉它是这样的:

您的bubble_sort 函数接受一个指针,但您将其传递给一个整数。

指针、地址、数组和整数是重要的C概念,恐怕你必须复习你的基本C知识;阅读一些参考代码将帮助您了解如何解决您的问题。我知道你很可能是 C 的新手,这个答案是一个答案,但不能立即解决你的问题,但是这里要解释的东西太多了,如果其他人出现,它也对你没有帮助将您的问题标记为低质量问题。

【讨论】:

  • 格式说明符连同传递给fscanf 的值是正确的(大部分情况下)。 %s 期望 char*namesurname 成员在表示为参数时都将转换为。如果 OP 的 fscanf 代码有任何问题,是 (a) 未能检查成功/失败的结果,以及 (b) 未能将 %s 格式说明符限制为所传递的字符缓冲区的大小。代码中有很多错误。为什么你挑出一些正确的东西(通过 OP 所做的 namesurname)似乎很奇怪。
  • "为什么你认为有时可以在 fscanf 中使用变量的地址(使用 & 前缀运算符)有时不可以?" --> C 规范是这样做的 int n, i; float x; char name[50]; n = fscanf(stdin, "%d%f%s", &amp;i, &amp;x, name); 你是在暗示 C 规范和 OP 是错误的吗?
  • 不,chux,这表明你不明白char name[50] 使name 成为char*,一个指向数组中第一个char 的指针。同样,这是非常基本的 C!不过你说的很对,我的措辞很糟糕。我很抱歉!我试图传达的一点是,如果他对数组进行操作,他必须知道什么是指针,什么是对象本身。
【解决方案3】:
there were lots of problems with the code 
however the following should have all those problems corrected
and includes error checking


#include <stdio.h>
#include <stdlib.h> // exit
#include <string.h> // memcpy

#define MAX_GRADES (12)

struct student_grades
{
    int number;
    char name[10];
    char surname[10];
    int grade;
};




void bubble_sort(struct student_grades* pList, int n)
{ //Line 16
    long c, d;
    struct student_grades t;

    for (c = 0 ; c < (n - 1); c++)
    {
        for (d = 0 ; d <(n - c - 1); d++)
        {
            if (pList[d].number > pList[d+1].number)
            {
                /* Swapping */

                memcpy(&t, &pList[d], sizeof(struct student_grades));
                memcpy(&pList[d], &pList[d+1], sizeof(struct student_grades));
                memcpy(&pList[d+1], &t, sizeof(struct student_grades));
            } // end if
        } // end for
    } // end for
} // end function: bubble_sort


int main()
{
    FILE *stu = NULL;  // file tipinde değişken tutacak
    FILE *stub = NULL; // rises compiler warning about unused variable

    if( NULL == (stu= fopen("student.txt","r")) )
    { // then, fopen failed
        perror( "fopen for student.txt failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    if( NULL == (stub= fopen("stu_order.txt","a")) )
    { // then, fopen failed
        perror( "fopen for stu_order.txt failed" );
        fclose(stu); // cleanup
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful


    struct student_grades stg[MAX_GRADES];
    char line[1000]; // should be enough for reading 4 fields

    int i=0;
    while((i<MAX_GRADES) && fgets(line, sizeof(line), stu) )
    {
        if( 4 != sscanf(line," %d %s %s %d",
                        &stg[i].number,
                        stg[i].name,
                        stg[i].surname,
                        &stg[i].grade) )
        { // fscanf failed
            perror( "fscanf failed" );
            fclose(stu); // cleanup
            fclose(stub);
            exit( EXIT_FAILURE );
        }

        // implied else, fscanf successful

        //fprintf(stub,"%d  %s  %s  %d\n",stg[i].number,stg[i].name,stg[i].surname,stg[i].grade);

        ++i;
    } // end while

    bubble_sort(stg,i);    //Line 59

    int j;
    for(j=0;j<i;j++)
    {
        fprintf(stub,"%d  %s  %s  %d\n",
                stg[1].number,
                stg[1].name,
                stg[1].surname,
                stg[1].grade); //control that is bubble  success?
    } // end for

    fclose(stu); // leanup
    fclose(stub);
    return 0;
} // end function: main

【讨论】:

  • C 支持通过赋值复制本机结构。memcpy 不是必需的。
猜你喜欢
  • 1970-01-01
  • 2018-06-12
  • 2021-06-09
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
相关资源
最近更新 更多