for循环和/或函数出错

时间:2015-12-12 22:42:22

标签: c function for-loop

这是我的代码:

#include <stdio.h> 
#include <string.h> 
#define numlines 2201
#define linelen 99 


typedef struct 
{ 
    char class[99]; 
    char age[99];
    char gender[99]; 
    char survived[99]; 
} Passenger; 


int cmpStruct(Passenger pa, Passenger Query);

Passenger lineToStruct(char line[]); 

Passenger queryToStruct(char line[]);

int findMyChar(char str[], int size, int start, char ch);

int Computation(Passenger Query, Passenger allPassengers[]);




int main(void) 
{

    FILE *fp;   
    fp = fopen("Titanic.txt", "r");  
    if (fp == NULL) 
    {
        printf("Error opening file %s, \n", "Titanic.txt");
        return -1; 
    }




    Passenger allPassengers[numlines];
    int n = 0;
    while(1)
    {
        char line[numlines];
        if (fgets(line, linelen, fp) == NULL) 
        { 
            break;
        }

        allPassengers[n] = lineToStruct(line);
        n++;    
    }


    fclose(fp);


    Passenger Query;

    char query[99];

    while (1)
    { 
        printf("\nType 1 for query, or 0 to quit: "); 

            int begin; 

        scanf("%d",&begin);

        if (begin == 0) 
        {         
            printf("Bye Bye!\n\n"); 
            return 0; 
        } 

        while(1)
        {
            printf("Type in the query that you want to know");
            printf(" sample query is: class=first,age=adult,gender=male \n");
            scanf("%s", &query);  
            break;
        }

        int iteration1;
        int iteration2;
        int iteration3; 

        if(query == "all")
        {
            for(iteration1=1; iteration1<=4;iteration1++)
            {

                if(iteration1==1)
                {
                    strcpy(Query.class, "first");
                }
                if(iteration1==2)
                {
                    strcpy(Query.class, "second");
                }
                if(iteration1==3)
                {
                    strcpy(Query.class, "third");
                }
                if(iteration1==4)
                {
                    strcpy(Query.class, "crew");
                }

                for(iteration2=1; iteration2<=2;iteration2++)
                {
                    if(iteration2==1)
                    {
                        strcpy(Query.age, "adult");
                    }
                    if(iteration2==2)
                    {
                        strcpy(Query.age, "child");

                    }

                    for(iteration3=1; iteration3<=2;iteration3++)
                    {
                        if(iteration3==1)
                        {
                            strcpy(Query.gender, "male");
                        }   
                        if(iteration3==2)
                        {
                            strcpy(Query.gender, "female");

                        }

                        Computation(Query, allPassengers);

                    }
                }
            }
        }

        else
        {
            Query = queryToStruct(query); 

            float totalPassengers = 0; 
            float survived = 0;        
            float percentage;
            int i;
            for(i=0;i<numlines;i++)
            { 

                if (cmpStruct(allPassengers[i],Query)==0)
                { 

                    totalPassengers++; 

                    if (strcmp(allPassengers[i].survived,"yes")==0)
                    {  
                        survived++; 
                        if (cmpStruct(allPassengers[i],Query)==1)
                        {
                            printf("error");
                            break;
                        }
                    } 

                } 

            }


            percentage = survived/totalPassengers*100; 
            printf("\nResults:\n"); 
            printf("\nClass = %s\nAge = %s\nGender = %s\n\n",Query.class,Query.age,Query.gender); 


            if (totalPassengers == 0)
            { 
                printf("There was an error within the query\n"); 
            } 
            else 
            { 
                printf("%.0f passengers are in the query (of 2201), %.0f of them survived\n",totalPassengers,survived); 
            } 

            if (totalPassengers != 0)
            { 
                printf("Chance of survival is %.1f%c\n",percentage,'%');
            } 
        } 
    }
}



int findMyChar(char str[], int size, int start,  char ch)
{

    int i; 
    for(i=start;i<size;i++)
    {
        if(str[i]==ch)
        { 
            return i; 
        } 
    } 
    return -1;
} 


Passenger lineToStruct(char line[])
{ 

    Passenger passengerL; 

    int classInd = findMyChar(line, 99, 0, '=');

    char class = line[classInd+1];

    switch (class)
    {

        case 'f':
            strcpy(passengerL.class, "first");          
            break;      
        case 's':
            strcpy(passengerL.class, "second");
            break;      
        case 't':
            strcpy(passengerL.class, "third");
            break;          
        case 'c':
            strcpy(passengerL.class, "crew");
            break;      
        case 'a':
            strcpy(passengerL.class, "any");
            break;      
    }

    line[classInd] = '!';   


    int ageInd = findMyChar(line, 99, 0, '=');
    char age = line[ageInd+2];

    switch (age)
    {
        case 'd':
            strcpy(passengerL.age, "adult");
            break;                  
        case 'h':
            strcpy(passengerL.age, "child");
            break;              
        case 'n':
            strcpy(passengerL.age, "any");
            break;      
    }

    line[ageInd]= '!';

    int genderInd = findMyChar(line, 99, 0, '=');

    char gender = line[genderInd+3];


    switch (gender)
    {
        case 'l':
            strcpy(passengerL.gender, "male");
            break;          
        case 'm':
            strcpy(passengerL.gender, "female");
            break;          
        case 'y':
            strcpy(passengerL.gender, "any");
            break;              

    }


    line[genderInd] = '!';

    int survivedInd = findMyChar(line, 99, 0, '=');

    char survived = line[survivedInd+1];

    switch (survived)
    {
        case 'y':
            strcpy(passengerL.survived, "yes");
            break;          
        case 'n':
            strcpy(passengerL.survived, "no");
            break;              
    }

    line[classInd] = '=';   
    line[ageInd] = '=';
    line[genderInd] = '=';

    return passengerL;

} 


Passenger queryToStruct(char line[])
{ 

    Passenger passengerQ; 

    int classInd = findMyChar(line, 99, 0, '=');
    char class = line[classInd+1];

    switch (class)
    {
        case 'f':
            strcpy(passengerQ.class, "first");
            break;              
        case 's':
            strcpy(passengerQ.class, "second");
            break;          
        case 't':
            strcpy(passengerQ.class, "third");
            break;          
        case 'c':
            strcpy(passengerQ.class, "crew");
            break;      
        case 'a':
            strcpy(passengerQ.class, "any");
            break;  

    }

    line[classInd]= '!';
    int ageInd = findMyChar(line, 99, 0, '=');
    char age = line[ageInd+2];

    switch (age)
    {
        case 'd':
            strcpy(passengerQ.age, "adult");
            break;
        case 'h':
            strcpy(passengerQ.age, "child");
            break;      
        case 'n':
            strcpy(passengerQ.age, "any");
            break;

    }

line[ageInd] = '!';


    int genderInd = findMyChar(line, 99, 0, '=');
    char gender = line[genderInd+3];


    switch (gender)
    {
        case 'l':
            strcpy(passengerQ.gender, "male");
            break;              
        case 'm':
            strcpy(passengerQ.gender, "female");
            break;      
        case 'y':
            strcpy(passengerQ.gender, "any");
            break;

    }

    line[classInd] = '=';   
    line[ageInd] = '=';


    return passengerQ;

}

int cmpStruct(Passenger pa, Passenger Query) 
{
    if (strcmp(Query.class, "any") != 0 && strcmp(Query.class, pa.class) != 0)
        return 1;

    if (strcmp(Query.age, "any") != 0 && strcmp(Query.age, pa.age) != 0)
        return 1;

    if (strcmp(Query.gender, "any") != 0 && strcmp(Query.gender, pa.gender) != 0)
        return 1;

    return 0;
}

int Computation(Passenger Query, Passenger allPassengers[])
{        
    int totalPassengers = 0;

    int survived = 0;  

    float percentage;

    int i;

    for(i=0;i<numlines;i++)
    { 
        if (cmpStruct(allPassengers[i],Query)==0)
        { 
            totalPassengers++;  

            if (strcmp(allPassengers[i].survived,"yes")==0)
            {  
                survived++; 
                if (cmpStruct(allPassengers[i],Query)==1)
                {
                    printf("error");
                    break;
                } 

            }

        } 

    }

    percentage = survived/totalPassengers*100; 
    printf("\nResults:\n"); 
    printf("\nClass = %s\nAge = %s\nGender = %s\n\n",Query.class,Query.age,Query.gender); 

    if (totalPassengers == 0)
    { 
        printf("There was an error within the query\n");
    } 
    else 
    { 
        printf("%.0f passengers are in the query (of 2201), %.0f of them survived\n",totalPassengers,survived); 
    } 

    if (totalPassengers != 0)
    { 
        printf("Chance of survival is %.1f%c\n",percentage,'%');
    }

}

Text File

Output

该程序的目标是使用给定的文本文件(Titanic.txt)并打印出任何给定查询的生存机会。可以输入查询,如:

  

类=第一,年龄=儿童,gender = male的

     

类=船员,年龄=成人,性别=女性

     

类=任何,年龄=成人,性别=任何

     

所有

     

可能的班级是第一,第二,第三和船员,可能的年龄是成人或儿童,可能的性别是男性和女性。

所以,我遇到的问题是当我输入'all'时我的程序没有产生结果。这在我给出的输出图中描述。我认为错误是在我的主循环中使用的for循环中,或者是在我程序结束时使用的计算函数中。

1 个答案:

答案 0 :(得分:1)

主要问题

if(query == "all")

错了。它比较了两个指针。它没有比较字符串。你需要使用:

if( strcmp(query, "all") == 0 )

其他错误

在使用-Wall标志进行编译时,我从gcc收到以下消息。

soc.c: In function ‘main’:
soc.c:83:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[99]’ [-Wformat=]
          scanf("%s", &query);  
          ^
soc.c:91:16: warning: comparison with string literal results in unspecified behavior [-Waddress]
       if(query == "all")
                ^
soc.c: In function ‘Computation’:
soc.c:439:7: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]
       printf("%.0f passengers are in the query (of 2201), %.0f of them survived\n",totalPassengers,survived); 
       ^
soc.c:439:7: warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Wformat=]
soc.c:447:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

可以通过更改

来修复第一个
scanf("%s", &query);  

scanf("%s", query);  
            ^^^ Remove the &

第二个是主要问题。

可以使用格式字符串中的%d代替%.0f修复第三个。

可以通过将Computation的返回类型更改为void来修复第四个问题。由于您没有从函数返回任何内容,并且调用它的位置不期望返回值,因此将返回类型更改为void似乎是有意义的。

还有一个错误未被编译器捕获。它是以下一行:

percentage = survived/totalPassengers*100; 

由于整数除法,这将导致0被分配到percentage。将其更改为:

percentage = 1.0*survived/totalPassengers*100; 

percentage = 100.0*survived/totalPassengers;