2016-10-07 46 views
2

我從一個文本文件中讀取15個數字閱讀的數字,每個數字在一個新行:C程序 - 驗證從文本文件

 
1 
2 
3 
4 
5 
10 
12 
13 
14 
15 
21 
22 
23 
24 
26 

正如你可以從代碼中看到我需要的號碼進行驗證,使其小於26,否則終止程序。

此刻我只有在將其插入到數組(numArray)後才能進行驗證。有沒有更簡單的方法(在插入數組之前驗證)

問題是,我似乎無法得到正在讀取的文本文件中的實際。這就是爲什麼我使用數組(int x = numArray [i];)上的循環索引來驗證它。

任何幫助表示讚賞,我很新的C編程。謝謝。

FILE *myFile = fopen(dataset.txt, "r"); 
int numArray[15]; 

if (myFile != NULL) { 

    for (int i = 0; i < sizeof(numArray); i++) 
    { 
     //insert int to array 
     fscanf(myFile, "%d", &numArray[i]); 

     //Validate number 
     int x = numArray[i]; 
     if (x > 25) { 
      printf("Invalid number found, closing application..."); 
      exit(0); 
     } 
    } 

    //close file 
    fclose(myFile); 
} 
else { 
    //Error opening file 
    printf("File cannot be opened!"); 
} 
+0

1.如果文件的其他字符不只是數字,請檢查'fscanf'的返回值。 2.爲什麼你要把數字放在數組中,是後續代碼的必要步驟?無論如何,你並不是真的插入任何東西,你只是在數組索引處設置值(插入通常意味着要移位元素以便在中間留出空間)。 – hyde

+2

你的循環將超出數組的界限。 'sizeof'運算符給你***字節的大小***,而不是元素的數量。對於實際的數組(例如'numArray'),可以通過將整個數組的大小除以單個元素的大小(即sizeof numArray/sizeof numArray [0])來獲得元素的數量。 –

回答

1

當然,您可以將其存儲在局部變量中,並且只有在有效時才進行賦值。但既然你打電話exit(0)如果無效它不會改變任何東西。我想你想從循環中取代break

順便說一句,你的循環是錯誤的。您必須將sizeof(numArray)除以一個元素的大小,否則您將循環太多次,並且如果輸入文件中的數字太多(如果我還添加了文件結束測試)

if (myFile != NULL) { 

    for (int i = 0; i < sizeof(numArray)/sizeof(numArray[0]); i++) 
    { 
     int x; 
     //insert int to array 
     if (fscanf(myFile, "%d", &x)==0) 
     { 
      printf("Invalid number found/end of file, closing application...\n"); 
      exit(0); // end of file/not a number: stop 
     } 

     //Validate number 
     if (x > 25) { 
      printf("Invalid number found, closing application...\n"); 
      exit(0); 
     } 
     numArray[i] = x; 
    } 

    //close file 
    fclose(myFile); 
}