文件输入错误

File input Error

本文关键字:错误 输入 文件      更新时间:2023-10-16

我正试图在我的代码中输入一个文件,该文件包含一个带有换行符的整数列表我使用以下代码输入到文件中的内容

int main()
{
FILE* f = fopen("Integers.txt", "r");
int n = 0, i = 0;
int numbers[5]; // assuming there are only 5 numbers in array input
while( fscanf(f, "%dn", &n) > 0 ) // parse %d followed by 'n'
{
    numbers[i++] = n;
}
fclose(f);
}

我有分段错误,所以请帮忙。

试试这个。。。。。

main()
{
 FILE* f = fopen("Integers.txt", "r");
 int n,i;
 int numbers[5]; // assuming there are only 5 numbers in array input
 for (i=0; i<5; i++)
 {
 fscanf(f, "%d", &n)
 numbers[i] = n;
 }
fclose(f);
}

您可能应该尝试一下,因为数组numbers只是5

int main()
{    
int n = 0, i = 0;
int numbers[5]; // assuming there are only 5 numbers in array input
FILE* f = fopen("Integers.txt", "r");
if (f != NULL)
{    
    for (i=0; i<(sizeof(numbers)/sizeof(int)); i++)
    {
        if (fscanf(f, "%dn", &n) > 0)
            numbers[i] = n;
        else
            break;
    }
    fclose(f);
}
}

数组numbers[5]在堆栈中,越界访问它将损坏堆栈。