2016-03-21 11 views
1
#include <stdio.h> 


int getIntegers(char *filename,int a[]); 

int main(void) { 
    ///// 
    FILE *fp; 
    char file[10] = "random.txt"; 
    fp = fopen(file, "w"); 
    fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n"); 
    fclose(fp); 
    ///// 

    int i; 

    int a[100]; 
    int n = getIntegers(file,a); 
    //Here i want to print out what i got from getIntegers. What it should put out = "1 2 -34 56 -98 42516547 -34 56 12345" 
    if (n > 0) 
    { 
     puts("found numbers:"); 
     for(i = 0;i < n; i++) 
      { 
       printf("%d ",a[i]);  
      } 
     putchar('\n'); 
    } 
    return 0; 
} 

int getIntegers(char *filename, int a[]) 
{ 
    int c, i; 
    FILE *fp; 
    fp = fopen(filename, "r"); 
//I want what this code does to be done with the commented code under it. This will give "1 2 -34 56 -98 42516547" 
    while (fscanf(fp,"%d",&i)==1) 
    { 
     printf("%d ",i); 
    } 
    fclose(fp); 

// I want this code to give "1 2 -34 56 -98 42516547 -34 56 12345" 
// while ((c = fgetc(fp)) != EOF) 
// {   
//  for(i = 0; i < c;i++) 
//  { 
//   fscanf(fp, "%1d", &a[i]); 
//  } 
// } 
// return i; 
} 

ファイルに数字と単語/文字があります。このコードでは、最初の文字まで整数を取得しますが、EOFまで続行します。そして、それらの数字を返して、メインでそれらを印刷します。私は試しましたが、うまく動作しませんでした。これを行うにはどうすればよいでしょうか?または私は何が間違っている。ファイルを読み込み、整数だけを取得して終了まで続きます

+0

は 'getIntegersをint型()'任意の値を返しません。コードは 'a []'に何も保存しません。 – chux

答えて

0

複数の問題:

int getIntegers()

は、任意の値を返しません。コードは a[]に何も保存しません。配列制限は強制されません。

コメントコードは、戻り値fscanf()をチェックしません。

fscanf()が0を返してからもう一度やり直すと、コードで1文字を消費する必要があります。 fscanf(fp, "%d", &a[i]) 0を返すが、それは入力を意味

は非数値入力のいずれかを消費しませんでしたfscanf()数値ではありません。 1文字を読んで、もう一度やり直してください。

#include <stdio.h> 
#define N 100 

int getIntegers(char *filename, int a[], int n); 

int main(void) { 
    FILE *fp; 
    char file[] = "random.txt"; 
    fp = fopen(file, "w"); 
    if (fp == NULL) { 
    fprintf(stderr, "Unable to open file for writing\n"); 
    return -1; 
    } 
    fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n"); 
    fclose(fp); 

    int a[N]; 
    int i; 
    int n = getIntegers(file, a, N); 

    puts("found numbers:"); 
    for (i = 0; i < n; i++) { 
    printf("%d ", a[i]); 
    } 
    putchar('\n'); 

    return 0; 
} 

int getIntegers(char *filename, int a[], int n) { 
    int i; 
    FILE *fp = fopen(filename, "r"); 
    if (fp) { 
    for (i = 0; i < n; i++) { 
     int cnt; 
     do { 
     cnt = fscanf(fp, "%d", &a[i]); 
     if (cnt == EOF) { fclose(fp); return i; } 
     if (cnt == 0) fgetc(fp); // Toss 1 character and try again 
     } while (cnt != 1); 
     // printf("%d ", i); 
    } 
    fclose(fp); 
    } 
    return i; 
} 

出力

found numbers:1 2 -34 56 -98 42516547 -34 56 12345 
+0

私が持っていた問題を解説してくれてありがとう。そのことを念頭に置いて、私はずっと良く理解できました。 – Teted

関連する問題