0
#include<iostream.h>
#include<fstream.h>
using namespace std;
ifstream f("nr.txt");
int n=0,i=1,aux[100],j=1,m,v[100];
int main()
{     
    while(f>>v[i])
    {
        i++;
    }
    n=i;
    for(i=1;i<=n;i++)
        cout<<v[i]<<" ";
}

我的“nr.txt”文件包含以下数字:-3 -10 0 7 -5 7 51 -800 6 3798 当我运行程序时,它应该显示文件中的所有这些数字,但它会显示更多(0)。 ..为什么是这样?如果我在主函数中声明数组,它会显示 6226116 而不是 0。

4

1 回答 1

0

So i starts at 1, which means that if there is only one number, the while cycle runs once, setting i to 2, and then n is set to i which becomes also 2. When you print the numbers you go from 1 to n (inclusive), which is 1 and 2, but you only have one number in the array.

In short, you're printing one more element than you should.

于 2013-05-26T11:41:27.440 回答