2016-03-21 16 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()'不返回任何值。代碼不會在'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