0
I have to perform a work that consists in the manipulation of values present in a.txt file, but I’m having difficulties with reading these values.
The.txt file is arranged as follows:
n
Nome1
Wage 1
Data1
Department1 Name2
Salarie2
Data2
Department2
...
Nomen
Salarion
Datan
Departamenton
Where n would be the number of employees listed, and the following lines contain the values for name, salary, date of admission and department of each employee.
I am storing these values in a struct vector of size n, and for cases where the name does not have whitespace, the code works well. However, if the employee’s name is "Fulato de Tal", for example, the program works incorrectly.
What function or change in the code could I use to fix this problem? Below is the part of the code in question:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int dia;
int mes;
int ano;
}Data;
typedef struct{
char nome[50];
double salario;
Data data;
char departamento[50];
}funcionario;
int main(){
FILE *arq;
arq = fopen("teste.txt", "r+");
if (arq == NULL){
printf("Problemas na criacao do arquivo!\n");
system("pause");
exit(1);
}
int n;
fscanf(arq, "%d", &n);
funcionario vetor[n];
for (int i = 0; i < n; i++){
fscanf(arq, "%s", vetor[i].nome);
fscanf(arq, "%lf", &vetor[i].salario);
fscanf(arq, "%d/%d/%d", &vetor[i].data.dia, &vetor[i].data.mes, &vetor[i].data.ano);
fscanf(arq, "%s", vetor[i].departamento);
}
And what is the separator from one field to another within a line? How you can have side effects with using the fscanf function (like the one you reported) evaluate the use of the fgets function for reading an entire line and then treat the fields in the string read.
– anonimo