-3

I am having difficulty populating an array from a .txt file. I can do it without the while loop if I already know the size of the file. However, once I incorporate a while loop to extract the file size the input odes not configure correctly. Pleas take a look over my code an let me know if you see where I am going wrong.

#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;
}
Gholamali-Irani
  • 3,851
  • 5
  • 24
  • 55
Jay
  • 1
  • 1
  • 4
    Please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Some programmer dude Jan 21 '18 at 17:40
  • As another problem, once the first loop is over, the file is beyond the end. What do you then think happens when you attempt to read from it? – Some programmer dude Jan 21 '18 at 17:41
  • Alternatively you can use the stringbuffer `#include std::stringstream buffer << file.rdbuf(); string fileContents = buffer.str();` – Kunal Mukherjee Jan 21 '18 at 17:41
  • After counting you are at EOF. How many numbers can you read from that position? –  Jan 21 '18 at 17:42
  • And if you don't know the number of value in the file beforehand, use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector). Together with [`std::istream_iterator`](http://en.cppreference.com/w/cpp/iterator/istream_iterator) filling that vector with numbers from the file is a *single line*. – Some programmer dude Jan 21 '18 at 17:42
  • Use std::vector and push_back. –  Jan 21 '18 at 17:43

1 Answers1

0

To read an arbitrary amount of numeric values from a text-file, all you need is an std::vector and a couple of std::istreambuf_iterator objects.

Then is as simple as

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

std::vector<int> values(std::istreambuf_iterator<int>(input),
                        std::istreambuf_iterator<int>());

That's it. Those four lines of code (counting the empty line) will read all int values from the text file Instance_1.txt and place them into the vector values.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550