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

标签 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;
}

请帮忙

最佳答案

我同意@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];

注意:我没有检查是否成功读取,但这样做是一个很好的做法。

关于c++ - 从文件中读取整数并将它们存储在数组 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26979236/

相关文章:

c++ - setter 方法中的 make_shared 行为类似于创建拷贝

c++ - 如果从QRunnable或其他线程调用Qt信号和插槽,则它们不起作用

c# - 托管 .net 的 C++ 程序将对象从 C++ 公开到 C#

c++ - SDL : blitting on background instead of screen?

C++单例模板类

c++ - Boost Socket/Acceptor 无法在同一端口上监听/连接?

c++ - 为什么不打开 char 值达到 case 0xC2?

c++ - "does not have class type"使用map容器的类成员函数实现错误

c++ - 检查是否在 unix 中加载了共享对象

c++ - 删除不完整类型在 C++ 中不是错误时,是否存在真实案例?