2013-10-27 3 views
1

У меня следующий код:не fscanf сканирования значения правильно

#include <stdio.h> 
#include <string.h> 
#define SIZE 6 
struct books{ 
    char name[100],author[100]; 
    int year,copies; 
    }; 
struct books book1[SIZE],book2[SIZE],*list; 

main() 
{ 
    unsigned i; 

    char line [ 100 ],temp1[100],temp2[100],c; /* line size */ 
    size_t len; 

    FILE *file; 

    file=fopen("input.txt","rw"); 

    int k=0; 
    for(i=0; fgets (line, sizeof line, file) ; i++) /* read a line */ 
    { 
    len = strlen(line); 
    while (len && line[len-1] == '\n') line[--len] = 0; 
    switch (i % 4) 
    { 
     case 0: /* handle first line here */ 
      fscanf(file, "%[^\n]s",book1[k].author); 
      break; 
     case 1: /* handle second line here */ 

      fscanf(file, "%[^\n]s",book1[k].name); 
      break; 
     case 2: /* handle third line here */ 

      fscanf(file, "%[^\n]s",temp1); 
      book1[k].year=atoi(temp1); 
      break; 
     case 3: /* handle fourth line here */ 

      fscanf(file, "%[^\n]s",temp2); 
      book1[k].copies=atoi(temp2); 
      break; 
    } 
    if(i % 4 == 3) 
    { 
     k++; 
    } 
    } 
    fclose(file); 

    i=0; 
    while(i<SIZE) 
    { 
    printf("##########################################################################\n"); 
    printf("\nAuthor: %s\nBook: %s\nYear of Publication: %d\nNo of Copies: %d\n\n",book1[i].author,book1[i].name,book1[i].year,book1[i].copies); 
    printf("##########################################################################\n"); 
    i++; 
    } 

} 

Входной файл:

A 
Ruby On Rails 
2004 
100 
J 
Learn Python Easy Way 
1967 
100 
D 
Harry Potter and the Sorcerer's stone 
2012 
150 
D 
Harry Potter and the Sorcerer's stone 
3045 
140 
Z 
Harry Potter and the Sorcerer's stone 
2013 
150 
K 
Inferno 
1993 
453 

Но мой вывод:

########################################################################## 

Author: Ruby On Rails 
Book: 2004 
Year of Publication: 100 
No of Copies: 0 

########################################################################## 
########################################################################## 

Author: Learn Python Easy Way 
Book: 1967 
Year of Publication: 100 
No of Copies: 0 

########################################################################## 
########################################################################## 

Author: Harry Potter and the Sorcerer's stone 
Book: 2012 
Year of Publication: 150 
No of Copies: 0 

########################################################################## 
########################################################################## 

Author: Harry Potter and the Sorcerer's stone 
Book: 3045 
Year of Publication: 140 
No of Copies: 0 

########################################################################## 
########################################################################## 

Author: Harry Potter and the Sorcerer's stone 
Book: 2013 
Year of Publication: 150 
No of Copies: 0 

########################################################################## 
########################################################################## 

Author: Inferno 
Book: 1993 
Year of Publication: 453 
No of Copies: 0 

########################################################################## 

Почему он пропускает первую строку? Что не так с этим кодом?

+0

«fscanf не сканирует значения правильно» - действительно. Вам лучше использовать 'fgets()', как я уже сказал. Держитесь подальше от 'scanf()', это зло и неинтуитивно. –

+0

После вызова 'fgets()', проанализируйте строку с помощью 'sscanf()'. Линия 'fscanf()' проверяет строку после строки, полученной с помощью функции 'fgets()'. – jxh

ответ

-1

Имел проблему similat. хотя это не ответ, но он исправит вашу проблему.

Сохраните первую строку входного файла пустым, и все будет работать нормально. Ответ на вопрос @anatolyg.

1
fgets (line, sizeof line, file) 

Этот код пропускает первую строку. Удалите его, и это будет хорошо.

Кстати, fscanf формат строки "%[^\n]s" не очень хорошо. Замените его на "%[^\n]\n" (или лучше, "%[^\n]%*c" - см. Комментарий от @chux), чтобы правильно читать строки. Или замените fscanf на fgets, чтобы сделать то же самое без этих строк в стиле фанк.

+1

Примечание: ''% [^ \ n] \ n "' не отличается от ''% [^ \ n] "'. Помещая '\ n' или' 'в строку формата, будет потреблено любое количество пробельных символов, включая любые, начинающиеся с строки _next_. Альтернативные форматы включают ''% [^ \ n] *% c "'. – chux

Смежные вопросы