C++ 从C+中的txt文件填充数组+;

C++ 从C+中的txt文件填充数组+;,c++,C++,从.txt文件填充数组时遇到困难。如果我已经知道文件的大小,我可以不使用while循环来完成。然而,一旦我加入while循环来提取文件大小,输入ODE就无法正确配置。请看一下我的代码,如果你看到我哪里出错了,请告诉我 #include "stdafx.h" #include <iostream> #include <cmath> #include <string> #include <fstream> int main() { using

从.txt文件填充数组时遇到困难。如果我已经知道文件的大小,我可以不使用while循环来完成。然而,一旦我加入while循环来提取文件大小,输入ODE就无法正确配置。请看一下我的代码,如果你看到我哪里出错了,请告诉我

#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>

int main()
{
    using namespace std;
    const char *inName_1 = "Instance_1.txt";
    const char *inName_2 = "Instance_2.txt";
    int arraySize_1 = 0, arraySize_2 = 0;
    int array_1[20];
    int array_2[20];
    int number;

    ifstream A2_file_1(inName_1);

    if (A2_file_1.fail())
    {
        cout << "File 1 not open!" << '\n';
    }

    while (!A2_file_1.eof())
    {
        arraySize_1++;
        A2_file_1 >> number;
    }

    if (A2_file_1.is_open())
    {
        for (int i = 0; i < arraySize_1; i++)
        {
            A2_file_1 >> array_1[i];
        }

        A2_file_1.close();
    }

    cout << "The size of the array 1 is: " << arraySize_1 << endl;

    for (int i = 0; i < arraySize_1; i++)
    {
        cout << array_1[i] << endl;
    }

    return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
int main()
{
使用名称空间std;
const char*inName_1=“Instance_1.txt”;
const char*inName_2=“Instance_2.txt”;
int arraySize_1=0,arraySize_2=0;
int数组_1[20];
int数组_2[20];
整数;
ifstream A2_文件_1(名称_1);
如果(A2_文件_1.fail())
{
库特数;
}
如果(A2_文件_1.is_open())
{
for(int i=0;i>数组_1[i];
}
A2_文件_1.close();
}

cout要从文本文件中读取任意数量的数值,只需一个和两个对象

那就简单到

std::ifstream input("Instance_1.txt");

std::vector<int> values(std::istreambuf_iterator<int>(input),
                        std::istreambuf_iterator<int>());
std::ifstream输入(“Instance_1.txt”);
std::矢量值(std::istreambuf_迭代器(输入),
std::istreambuf_迭代器();

就是这样。那四行代码(算上空行)将从文本文件
Instance_1.txt
中读取所有
int
值,并将其放入向量
值中

请将其作为另一个问题来阅读,一旦第一个循环结束,文件就超出了结尾。您认为在尝试读取时会发生什么情况?或者,您可以使用stringbuffer
\includede std::stringstream buffer计数后,您处于EOF。您可以从该位置读取多少个数字?如果您事先不知道文件中的值的数量,请使用。用文件中的数字填充该向量时,只需一行。