C 编写电话簿文件的项目

C 编写电话簿文件的项目,c,C,我编写了这个程序,但在fscanf 错误的注释 struct phone { char fname[20]; char lname[20]; char pnumber[20]; }; int main() { int x=0; int n; char s[100]; FILE * f; f = fopen("phone book","r"); if (f != NULL) { printf("file exist !\n

我编写了这个程序,但在
fscanf

错误的注释

 struct phone
 {
      char fname[20];
      char lname[20];
      char pnumber[20];
 };

int main()
{

 int x=0;
 int n;
 char s[100];

 FILE * f;

 f = fopen("phone book","r");

 if (f != NULL)
 {
     printf("file exist !\n");   
     while(!(feof(f)))
     {
           fscanf(f,"%s,%s,%s",s[x].fname,s[x].lname,s[x].pnumber);
           x++;
     }
 }

 printf("1-   add");
 printf("2-   query");
 scanf("%d",&n);

if(n==1)
    printf("%s",s[n].fname);

if(n==2)
    fclose(f);

}
struct phone s[100];  

s
声明为
chars[100]
,因此
s[x]
char
而不是
struct电话
。您需要将
s
声明为
struct phone s[100]和您的第一个问题将消失。

的错误

 'main':|
  request for member 'fname' in something not a structure or union|
  request for member 'lname' in something not a structure or union|
  request for member 'pnumber' in something not a structure or union|
  request for member 'fname' in something not a structure or union|
 : variable 's' set but not used [-Wunused-but-set-variable]|

 : control reaches end of non-void function [-Wreturn-type]|
 ||=== Build finished: 4 errors, 2 warnings (0 minutes, 0 seconds) ===|
改变

request for member 'fname' in something not a structure or union|
request for member 'lname' in something not a structure or union|
request for member 'pnumber' in something not a structure or union|
request for member 'fname' in something not a structure or union|
: variable 's' set but not used [-Wunused-but-set-variable]|  

对于这个错误呢

 struct phone
 {
      char fname[20];
      char lname[20];
      char pnumber[20];
 };

int main()
{

 int x=0;
 int n;
 char s[100];

 FILE * f;

 f = fopen("phone book","r");

 if (f != NULL)
 {
     printf("file exist !\n");   
     while(!(feof(f)))
     {
           fscanf(f,"%s,%s,%s",s[x].fname,s[x].lname,s[x].pnumber);
           x++;
     }
 }

 printf("1-   add");
 printf("2-   query");
 scanf("%d",&n);

if(n==1)
    printf("%s",s[n].fname);

if(n==2)
    fclose(f);

}
struct phone s[100];  

由于
main
的返回类型是
int
(返回类型不是
void
的非
void
函数),您需要添加
返回0main

的右括号
}
之前的code>语句好吧,编译器是对的。你申报

control reaches end of non-void function [-Wreturn-type]|  
并尝试像访问结构数组一样访问其成员。它只是一个字符数组

我想你想做点像

char s[100];
这将声明一个包含100个struct phone的数组


另外,请注意,虽然(!feof(f))不建议在这种情况下使用:

格式化代码,但它是不可读的。---“fscanf中有一个问题”-是的,
fscanf()
本身就是问题所在,不要使用它。您可以使用
fgets()
从文件中读取行,然后使用
strchr()
strstr()
strtok\u r()
strtol()
解析每一行-->
struct phone s[100]