0

I am having difficulty using fscanf, since I can't read the data from the file while ignoring ;.

void main() {
    int i=0;
    STUDENT aln;
    FILE *fp;


    fp = fopen("Aluno.txt","r");
    //Verificar abertura do File
    checkfile(fp);
    while (!feof(fp)) {
        fscanf(fp,"%d%s%d%d%s%d%c\n",&aln.id,&aln.name,&aln.age,&aln.uc.id,&aln.uc.nome,&aln.class.id,&aln.class.name);
        //fscanf(fp, "%d%[^;];[^;];%d%[^;];%d%[^;];%[^;];%d%[^;];%c\n", &aln.id, &aln.name, &aln.age, aln.uc.id, aln.uc.nome, aln.class.id, aln.class.name);
        printf("Nome: %s\n",aln.name);
    }
    system("pause");

}

and this is the file content:

1;Ruben;15;1;Matematica;1;A
2;Ana;16;2;Portugues;1;A
3;Raquel;17;1;Matematica;2;B
4;Rui;16;2;Portugues;2;B
5;Vasco;15;3;Fisica;3;C
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • 2
    [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – melpomene Sep 29 '18 at 20:37
  • 5
    For a proper [MCVE], please include the expected and actual behavior, not just the input and a code dump. You haven't even explained what's going wrong beyond "having difficulty". – ShadowRanger Sep 29 '18 at 20:39
  • 2
    `if (fscanf(fp, "%d;%[^;];%d;%d;%[^;];%d;%c", ...) != 7) /*error*/;` – pmg Sep 29 '18 at 20:43
  • @pmg `%s;` is pretty much guaranteed to fail. – melpomene Sep 29 '18 at 20:43
  • Thanks @melpomene, edited – pmg Sep 29 '18 at 20:44
  • 1
    The use of `while(fgets(...) != NULL)` and `strtok` followed by data extraction from the tokens, is one way to tackle the problem. – Weather Vane Sep 29 '18 at 20:44
  • We can be fairly confident that passing `&aln.name` where you're expecting `fscanf()` to process a `%s` format is wrong — I can't think of a circumstance in which it would be formally correct. However, the problem is the type of the pointer, not the value (provided the name element of the `STUDENT` type is an array and not itself a pointer) and things will usually work out OK for you. Note that the MCVE requested should include the definition of the `STUDENT` structure type. Also, using `%c` to read `&aln.class.name` is surprising; names usually allow more than one character. – Jonathan Leffler Sep 29 '18 at 21:50
  • What result do you want if the line of input is not formed correctly? e.g. `"X;Ruben;15;1;Matematica;1;A"` – chux - Reinstate Monica Sep 30 '18 at 02:37

0 Answers0