2016-08-13 7 views
-1

今日私はlinux mintのCでテキストファイルを使用しようとしていますが、動作していません(テキストは表示されません)。それを解決するために私を助けてください。テキストファイルを使用していますが動作していません

click here to see the picture

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int account; 
    char name[30]; 
    float balance; 
    FILE *fp; 
    if((fp = fopen("tin", "w")) == NULL) { 
     printf("File could not be opened\n"); 
     exit(1); 
    } 
    else { 
     printf("Enter the account, name, and balance.\n"); 
     printf("Enter EOF to end input.\n"); 
     printf("?"); 
     scanf("%d%s%f", &account, name, &balance); 
     while(!feof(stdin)) { 
      fprintf(fp, "%d %s %2.f\n", account, name, balance); 
      printf("?"); 
      scanf("%d%s%f", &account, name, &balance); 
     } 
     fclose(fp); 
    } 
    return 0; 
} 

私は私の端末でこのコードを実行すると、私はthis

はどうもありがとうございまし得ます。

+0

入力を表示します。 – BLUEPIXY

+0

ご迷惑をおかけして申し訳ありません。 –

+0

あなたが直面している正確なエラーを共有することができれば、それは良いでしょう、そのコンパイルかランタイムエラー –

答えて

0

fgetsを使用して入力をキャプチャし、sscanfを使用して入力を解析することを検討してください。成功したかどうかを確認するには、sscanfの戻り値を確認してください。これにより空白行の入力によりプログラムを終了させることができます。 EOFよりも少し便利です。

#include <stdio.h> 
#include <stdlib.h> 

#define SIZE 256 

int main() 
{ 
    int account; 
    char name[30]; 
    char input[SIZE]; 
    float balance; 
    FILE *fp; 
    if((fp = fopen("tin", "w")) == NULL) { 
     printf("File could not be opened\n"); 
     exit(1); 
    } 
    else { 
     do { 
      printf("Enter the account, name, and balance.\n"); 
      printf("Enter at ? to end input.\n"); 
      printf("?"); 
      if (fgets (input, SIZE, stdin)) { 
       if ((sscanf (input, "%d%29s%f", &account, name, &balance)) == 3) { 
        printf ("adding input to file\n"); 
        fprintf(fp, "%d %s %2.f\n", account, name, balance); 
       } 
       else { 
        if (input[0] != '\n') { 
         printf ("problem parsing input\nTry again\n"); 
        } 
       } 
      } 
      else { 
       printf ("problem getting input\n"); 
       exit (2); 
      } 
     } while(input[0] != '\n'); 
     fclose(fp); 
    } 
    return 0; 
} 
+0

うわー!それは非常に便利なコードです、あなたの助言に感謝します。 –

関連する問題