简体   繁体   中英

Putting data in files with for

int main()
{
 FILE*arq;
 char a[500];
  int i,f;
  arq=fopen("test.txt","w+");
 for(i=0;i<5;i++){
  printf("Type the name:");
  fgets(a,500,stdin);
  fprintf(arq,"%s",a);
  printf("Enter the age");
  fscanf(arq,"%d", f);
  fprintf(arq, "%d", f);
 }
fclose(arq);
return 0;
}

I cannot put the name and age in the file because after typing the name it skips the typing of the age

You've failed to pass a pointer to the variable that will hold the result when calling fscanf() . It should be:

fscanf(arq, "%d", &f);

The & tells the compiler you want to pass in the address of f rather than the value of f . This is necessary because the last argument of fscanf is the address where you want the result stored.

You need to give the address of the variable to be filled.

fscanf(arq,"%d", f);

->

fscanf(arq,"%d", &f);

For the first, reading a it is not necessary becaue it is an array, which gets treated as a pointer anyway.

First of all, you have to give the address of the variable to be filled. Secondly, you are reading from the file, which is empty until you close it, so it won't wait from input from stdin. It should be like this:

fscanf(stdin,"%d", &f);

This will leave a '\\n' in the buffer, which will be read by fgets. To prevent this, read the newline before the next iteration:

fgetc(stdin);

This code works for me:

int main()
{
 FILE*arq;
 char a[500];
 int i,f;
 arq=fopen("test.txt","w+");

 for(i=0;i<5;i++){
  printf("Type the name:");
  fgets(a,500,stdin);
  fprintf(arq,"%s",a);
  printf("Enter the age:");
  fscanf(stdin,"%d", &f);
  fprintf(arq, "%d", f);
  fgetc(stdin);
 }
 fclose(arq);
 return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM