从文件中读取整数并将它们存储在数组C ++中

时间:2014-11-17 18:20:04

标签: c++

这是我的代码,但我得到第一个数字的无限循环
我想从文件中读取整数并将它们存储在数组中

该文件包含:

  

8 5 12 1 2 7

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{    
    int n = 0; //n is the number of the integers in the file ==> 12
    int num;
    int arr[100];

    ifstream File;
    File.open("integers.txt");
    while(!File.eof())
    {
        File >> arr[n];
        n++;
    }

    File.close();

    for(int i=0;i<12;n++)
    {
        cout << arr[i] << " ";
    }

    cout << "done\n";
    return 0;
}

请帮助

2 个答案:

答案 0 :(得分:3)

你的循环应该是: -

for(int i=0; i < n ; i++)
{
    cout << arr[i] << " ";
}

答案 1 :(得分:3)

我同意@ravi,但我有一些注意事项:

如果你不知道文件中有多少个整数,而且文件只包含 整数,你可以这样做:

std::vector<int>numbers;
int number;
while(InFile >> number)
    numbers.push_back(number);

您需要#include<vector>


如果您读取文件中有多少整数然后使用循环读取它们会更好:

int count;
InFile >> count;
int numbers[count];       //allowed since C++11

for(int a = 0; a < count; a++)
    InFile >> numbers[a];

注意:我没有检查读取是否成功,但最好这样做。