0

我在我的函数 main 中收到错误,clrscr();但我认为我必须在使用时清除fflush(stdin);

我觉得我在这里遗漏了一些简单的东西,但如果有人能像我一样摆脱一些,我将不胜感激!

#include<stdio.h>
#include<conio.h>
#include<string.h>

struct person
{
        char name[10];
        int age;
};
typedef struct person NAME;
NAME  stud[10], temp[10];

void main()
{
     int no,i;

     void sort(int N);  /* Function declaration */

     clrscr();
     fflush(stdin);

     printf("Enter the number of students in the list\n");
     scanf("%d",&no);

     for(i = 0; i < no; i++)
     {
         printf("\nEnter the name of  person %d : ", i+1);
         fflush(stdin);
         gets(stud[i].name);

         printf("Enter the age of %d : ", i+1);
         scanf("%d",&stud[i].age);
         temp[i] = stud[i];
     }

     printf("\n*****************************\n");
     printf ("     Names before sorting     \n");
     /* Print the list of names before sorting */
     for(i=0;i<no;i++)
     {
            printf("%-10s\t%3d\n",temp[i].name,temp[i].age);
     }

     sort(no);       /* Function call */

     printf("\n*****************************\n");
     printf ("     Names after sorting     \n");
     printf("\n*****************************\n");
     /* Display the sorted names */
     for(i=0;i<no;i++)
     {
            printf("%-10s\t%3d\n",stud[i].name,stud[i].age);

     }
     printf("\n*****************************\n");
}          /* End of main() */

/* Function to sort the given names */
void sort(int N)
{
         int i,j;
         NAME temp;

         for(i = 0; i < N-1;i++)
         {
                for(j = i+1; j < N; j++)
                {
                    if(strcmp(stud[i].name,stud[j].name) > 0 )
                    {
                        temp    = stud[i];
                        stud[i] = stud[j];
                        stud[j] = temp;
                    }
                }
         }
}       /* end of sort() */
4

2 回答 2

2
  1. 把函数原型void sort(int N);放在外面main()
  2. 你没有(但你可以)clrscr()fflush(stdin). 在这种情况下,您的屏幕内容(您要清除的内容)与stdin.

你可以在这里阅读更多关于它的信息fflush()和使用它的动机。

于 2015-05-04T18:17:40.993 回答
2

我假设你得到一个编译错误。这是由您看到错误的行上方的行引起的。

正如@Catalyst 所建议的,它是由以下行引起的

void sort(int N);  /* Function declaration */`

因为 C 不允许在其他函数中本地声明函数(并且main 一个函数)。

你可以简单地修复它:

#include<stdio.h>
#include<conio.h>
#include<string.h>

struct person
{
        char name[10];
        int age;
};
typedef struct person NAME;
NAME  stud[10], temp[10];

void sort(int N);  /* Function declaration */


int main()    // void main is incorrect
{
     int no,i;

     clrscr();
     fflush(stdin);
...

另请注意,int main()而不是void main()。它在 Windows 上是无害的,但仍然不正确。

于 2015-05-04T18:19:57.987 回答