2016-05-11 11 views
-2

私はファイルから並列配列にスキャンしています。 文字列は正常にスキャンされますが、intとfloatは正しくスキャンされません。 ここで何がうまくいかないのですか? Num、human、およびcoolは、main関数で宣言された配列です。文字列とintをファイルからC言語の配列にスキャン

hello.txtのレコードの例: Angela, Merkel, 50, 10, 9.1

void read(int *lines, char first[ENTRY][FIRST], char last[ENTRY][LAST], int *num, int *human, float *cool) 
{ 
FILE *ifile; 
int i; 

ifile = fopen("hello.txt", "r"); 

fscanf(ifile, "%[^,] %*c %[^,] %*c %d %*c %d %*c %f", first[0], last[0], &num[0], &human[0], &cool[0]); 

printf("%s", first[0]); 
printf("%s\n", last[0]); 
printf("%d\n", num[0]); 
printf("%d\n", human[0]); 
printf("%f", cool[0]); 



fclose(ifile); 
} 
+5

まず、関数fscanf 'の戻り値をチェック()' ... –

+3

ショー 'hello.txt'、定義変数とどのようにこれを呼び出します。 – BLUEPIXY

+0

@ user9012ここで十分な質問を投稿できますか?私たちは大いに助けません – Sathish

答えて

0

は、関数のscanf家族と一緒に、宇宙は何も含まない、ホワイトスペースの任意の量に一致し、

fscanf(ifile, "%[^,] %*c %[^,] %*c %d %*c %d %*c %f", first[0], last[0], num, human, cool); 
+0

しかし、num、human、coolはmain関数で宣言された配列です。 – user9012

+0

それは問題ではありません。ポインタを 'read'に渡します。これは' fscanf'が必要とするものです。これらの配列のいくつかの数値を読み込むと、より複雑になります。 – GMichael

0

ファーストをお試しください、入力でも%*cを使用しないでください、それは必要ではありません。次に、フィールドを正常にスキャンするには、コンマをフォーマット文字列で指定する必要があります。第3に、scanfは常に期待値フィールドが入力されたことを確認するために戻り値をチェックします。この修正プログラムをお試しください:

void read(int *lines, char first[ENTRY][FIRST], char last[ENTRY][LAST], int *num, int *human, float *cool) 
{ 
    FILE *ifile; 

    ifile = fopen("hello.txt", "r"); 
    if (ifile == NULL) return; 

    int ret = fscanf(ifile, "%[^,], %[^,], %d, %d, %f", first[0], last[0], &num[0], &human[0], &cool[0]); 
    if (ret != 5) { // input file does not match the format 
     return; 
    } 

    printf("%s ", first[0]); 
    printf("%s\n", last[0]); 
    printf("%d\n", num[0]); 
    printf("%d\n", human[0]); 
    printf("%f\n", cool[0]); 

    fclose(ifile); 
} 
関連する問題