Save data from a txt file to an entire struct or manipulate struct. C

Asked

Viewed 293 times

0

I have a txt file that follows the template below. I want to save the balance as int, but with fgets I can’t get it. I’m wanting to save as int, because after the data is taken the program sorts them based on the balance. Is there any other way to do this???

nome
conta
saldo

Kelsen da Silva
54432
3456
William Malvezzi
67890
154998
Fulano de Tal 
14441
23987

The code that gave to take the data and print is like this.

struct conta{
  char nome[100];
  char conta[4];
  char saldo[10];
};

int main(){

int i = 0;
struct conta contas[10];
FILE *file = fopen("string.txt", "r");

while(!feof(file)){
    fgets(contas[i].nome, sizeof(contas[i].nome), file);
    fgets(contas[i].conta, sizeof(contas[i].conta), file);
    fgets(contas[i].saldo, sizeof(contas[i].saldo), file);
    i++;
  };

fclose(file);
}
  • A detail to note: a string in C is a string followed by the terminator character ' 0'. Like this char conta[4]; can store a string of up to 3 characters (plus terminator ' 0'). By your data (e.g.: 54432) you would need to declare char conta[6]; or more if the account has more digits.

1 answer

0


Whereas you can already get the balance data in the variable account[i]. balance, just transform the value of this string for integer, using the function atoi(). For this, you will need a new variable of type integer to allocate the result of this function. I suggest adding a new variable to your struct account, for example, int saldo_int. Taking advantage of its variable assignment loop with the file data, one can add, just below the last fgets() the function atoi() as follows:

while(!feof(file)){
  fgets(contas[i].nome, sizeof(contas[i].nome), file);
  fgets(contas[i].conta, sizeof(contas[i].conta), file);
  fgets(contas[i].saldo, sizeof(contas[i].saldo), file);
  contas[i].saldo_int = atoi(contas[i].saldo);
  i++;
};

So done, just implement the ordination you want based on the variable balances.int accounts.

Observing: as has not been informed, in case this structure of the struct should be fixed this way (3 variables with these exact names), two changes are required. First, to allow ordering, the field balance must be declared as int; and second, a auxiliary variable to perform the work that your variable accounts[i]. balance is doing (receiving data from the file) and then assigning its value to this variable through the atoi() function commented above (as stated earlier, this variable must be declared as integer within the struct). If the structure can be changed, just ignore this observation and implement the above code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.