Использование fscanf для чтения целых чисел, строк и действительных чисел - PullRequest
0 голосов
/ 26 апреля 2018

Не удается прочитать комбинацию целых чисел, строк и действительных чисел с помощью fscanf.Я признаю, что я начинающий программист на C, но я не понимаю, почему мой код не работает должным образом.

Содержимое sourcefile.txt, файла, используемого fscanf:

222 MSLET[Pa] 0-MSL 200507011200 200507021200 101226.063
223 MSLET[Pa] 0-MSL 200507011200 200507021200 9999.000
224 MSLET[Pa] 0-MSL 200507011200 200507021200 101217.063
222 PRMSL[Pa] 0-MSL 200507011200 200507021200 101226.063
223 PRMSL[Pa] 0-MSL 200507011200 200507021200 9999.000


My c-code is as follows:

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

int main (void)
{

  FILE *input;
  input = fopen("C:/sourcefile.txt", "r"); 
  char var[30], level[30];
  int loc, datecycle, datevalid;
  float value;


while (fscanf(input,"%d %[^ ] %[^ ] %d %d %f", &loc, var, level,         
&datecycle, &datevalid, &value) == 6) {

fscanf(input,"%d %[^ ] %[^ ] %d %d %f", &loc, var, level, &datecycle,  
&datevalid, &value);

printf("%d %s %s %d %d %f\n", loc, var, level, datecycle,
datevalid,value);

     }                                                                                                       

fclose(input);
return 0;               
}

Output from c-code:

223 MSLET[Pa] 0-MSL -1356451712 -1356441712 9999.000
222 PRMSL[Pa] 0-MSL -1356451712 -1356441712 101226.063
223 PRMSL[Pa] 0-MSL -1356451712 -1356441712 9999.000

Issue #1

1. Only 3 of the 5 lines were read. I don't understand why.

2. The printf output from datecycle and datevalid are not the same as the
input. I don't understand why.   

Issue #2

With respect to the string entries in column 2 (e.g. MSLET[Pa]), instead
of using [^ ] to read in the string (read until I encounter a space), I
may want to read until I encounter the "]" (e.g. the "]" in MSLET[Pa]).
My understand is that I would write [^]]. Is that correct?  

Any help that can be provided would be greatly appreciated.
...