0

I have an array of structs and they get saved into a file. Currently there are two lines in the file:

a a 1
b b 2

I am trying to read in the file and have the data saved to the struct:

typedef struct book{ 
    char number[11];//10 numbers 
    char first[21]; //20 char first/last name
    char last[21]; 
} info;

info info1[500]
into num = 0;

 pRead = fopen("phone_book.dat", "r");

 if ( pRead == NULL ){

        printf("\nFile cannot be opened\n");
}
 else{

      while ( !feof(pRead) ) {

            fscanf(pRead, "%s%s%s", info1[num].first, info1[num].last, info1[num].number);

            printf{"%s%s%s",info1[num].first, info1[num].last, info1[num].number); //this prints statement works fine

            num++;
     }

}
//if I add a print statement after all that I get windows directory and junk code.

This makes me think that the items are not being saved into the struct. Any help would be great. Thanks!

EDIT: Okay so it does save it fine but when I pass it to my function it gives me garbage code.

When I call it:

sho(num, book);

My show function:

void sho (int nume, info* info2){
     printf("\n\n\nfirst after passed= %s\n\n\n", info2[0].first); //i put 0 to see the first entry
}
4

2 回答 2

3
  1. 我想你的意思是int num = 0;,而不是into

  2. printf{... 是语法错误,printf(... 相反。

  3. 检查 的结果fscanf,如果不是 3,则它还没有读取所有 3 个字符串。

  4. 不要使用 ( f)scanf来读取字符串,至少在没有指定最大长度的情况下是这样:

    fscanf(pRead, "%10s%20s%20s", ...);
    

    但是,更好的是,fgets改用:

    fgets(info1[num].first, sizeof info1[num].first, pRead);
    fgets(info1[num].last, sizeof info1[num].last, pRead);
    fgets(info1[num].number, sizeof info1[num].number, pRead);
    

    (当然还要检查 的结果fgets

  5. 确保num不高于 499,否则会溢出info

    while(num < 500 && !feof(pRead)){.
    
于 2013-10-30T14:53:26.200 回答
0

1.-为了更好地处理错误,建议在验证结果中使用fgets(), 使用宽度。 2.-OP的用法容易误用-建议。sscanf()sscanf()
feof(pRead)fgets()

char buffer[sizeof(info)*2];   
while ((n < 500) && (fgets(buffer, sizeof buffer, pRead) != NULL)) {
  char sentinel;  // look for extra trailing non-whitespace.
  if (sscanf(buffer, "%20s%20s%10s %c", info1[num].first, 
      info1[num].last, info1[num].number, &sentinel) != 3) {
    // Handle_Error
    printf("Error <%s>\n",buffer);
    continue;
  }
  printf("%s %s %s\n", info1[num].first, info1[num].last, info1[num].number);
  num++;
}

顺便说一句:%s如果名字或姓氏中存在空格,则使用效果不佳。

于 2013-12-02T17:00:43.987 回答