文件输入错误

时间:2014-10-16 09:59:24

标签: c++ c

我正在尝试在My代码中输入一个包含New行整数列表的文件 我使用以下代码输入文件中的内容

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, "%d\n", &n) > 0 ) // parse %d followed by '\n'
{
    numbers[i++] = n;
}

fclose(f);
}

我遇到分段错误,请帮助。

2 个答案:

答案 0 :(得分:1)

您应该尝试这样做,因为数组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, "%d\n", &n) > 0)
            numbers[i] = n;
        else
            break;
    }
    fclose(f);
}
}

数组numbers[5]在堆栈中并且超出范围访问它会破坏堆栈。

答案 1 :(得分:1)

试试这个......

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);
}