[英]Error when trying to read in numbers from txt file in C
我是 C 編程的新手,當我運行我的程序時,我得到了一個 THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)。 我的代碼的目的是從包含正數和負數的 txt 文件中讀取數據並對其進行處理。
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
后
FILE *file = fopen("data.txt", "r");
說
if(file == 0) {
perror("fopen");
exit(1);
}
只是猜測,其余的代碼看起來沒問題,很可能這就是問題所在。
還值得注意的是,您的文件中可能有超過 100 個數字,在這種情況下,您將超出數組的大小。 嘗試用以下代碼替換 while 循環:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
您是否創建了文件“data.txt”並且是本地的?
touch data.txt
echo 111 222 333 444 555 > data.txt
檢查您的文件打開是否成功。
這是一個工作版本,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.