簡體   English   中英

將數據放入文件中

[英]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;
}

我無法在文件中輸入名稱和年齡,因為鍵入名稱后,它將跳過年齡的輸入

在調用fscanf()時,您無法傳遞指向將保存結果的變量的指針。 它應該是:

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

&告訴你想的地址通過編譯器f ,而不是價值f 這是必需的,因為fscanf的最后一個參數是您要將結果存儲在其中的地址。

您需要提供要填充的變量的地址。

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

->

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

首先,不必讀取a ,因為它是一個數組,無論如何它都會被當作指針。

首先,您必須提供要填充的變量的地址。 其次,您正在讀取文件,該文件在您關閉之前為空,因此不會等待來自stdin的輸入。 應該是這樣的:

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

這將在緩沖區中保留一個'\\ n',它將被fgets讀取。 為避免這種情況,請在下一次迭代之前閱讀換行符:

fgetc(stdin);

該代碼對我有用:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM