函数未返回预期的值

时间:2019-07-10 01:26:16

标签: c struct

我已将一个csv文件读入一个struct数组。然后程序要求用户输入国家名称。输入该命令后,我使用了strcmp,但是无论如何我都无法匹配它并返回国家

我确保正确读取了csv文件,并且还确保正确保存了用户输入

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

#define NAME_LENGTH 35
#define NUM_COUNTRY 32

struct country {
char countrys[35];
char group;
int goals;
int points;
}countries[NUM_COUNTRY];;

void search_by_country(void);
int find_country(char *countrys);
int read_line(char str[], int n);


int main(int argc, char *argv[])
{
 int i=0;
 int j;
 char code;
 FILE *worldcup;

if ((worldcup = fopen(argv[1], "r")) == NULL) 
{ 
    printf("%s can't be opened\n", argv[1]);
        return 1; 
}  

    fscanf(worldcup, "%*[^\n]");

        while(!feof(worldcup) && !ferror(worldcup)) 
        {
            fscanf (worldcup, "%[^,], %c, %d, %d", countries[i].countrys, 
            &countries[i].group, &countries[i].goals, &countries[i].points);
           i++;
           }
  for (j=0; j<i; j++){
  printf("%s,%c,%d,%d", countries[j].countrys, countries[j].group, 
  countries[j].goals, countries[j].points);
  }



for (;;) {
printf("Search by country: c\n");
printf("Quit:              q\n");
printf("Enter operation code: ");
scanf(" %c", &code);

while (getchar() != '\n')   /* skips to end of line */
  ;
switch (code) {
  case 'c': search_by_country();
            break;
 case 'q': return 0;
  default:  printf("Illegal code");
}
 printf("\n");

 }
 fclose(worldcup);
return 0;
}

int find_country(char *countrys)
{
int i;
for (i = 0; i < NUM_COUNTRY; i++)
 if (strcmp(countries[i].countrys, countrys) == 0)
  return i;
return -1;
}

void search_by_country(void)
{
char country_name[NAME_LENGTH+1];
  printf("enter country name:");
  read_line(country_name, NAME_LENGTH);
  printf("%s", country_name);

 int i = find_country(country_name);

if (i== -1){
 printf("that country did not play");
}
else{
   printf("%s,%c,%d,%d", countries[i].countrys, countries[i].group, 
   countries[i].goals, countries[i].points);
}}


int read_line(char str[], int n)
{
 int ch, i = 0;

 while (isspace(ch = getchar()))
 ;
 while (ch != '\n' && ch != EOF) {
   if (i < n)
    str[i++] = ch;
   ch = getchar();
  }
  str[i] = '\0';
  return i;
}

find_country最终应返回一个int值,我可以用该值打印出该国家的记录。但是我一直得到-1的回报,并且“那个国家没有参加比赛”

0 个答案:

没有答案