Search code examples
c++arraysfileifstream

Printing integers from a file using an array


I'm just beginning to learn C++ and I am having some trouble with a program. It's supposed to sort numbers from an external file. I've managed to successfully code the sorting algorithm, but I am having trouble working with the external file. I am just testing some things out in a separate program to gain an understanding of how things like ifstream work. I should be able to figure out how to implement it into my program once I gain a better understanding of how it works.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>


int main() {
    using namespace std;


    int count;
    ifstream InFile;

    InFile.open ("unsorted.txt");

InFile >> count;
int numbers[count];      

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

Currently, the output for this is 0x7ffc246c98e0 I am not sure why this is the case I'm just attempting to print my file of integers. Could anyone help explain what I am doing wrong? I'd be very thankful.


Solution

  • When you do

    cout << numbers << endl;
    

    you print the pointer to the first element of the array.

    You want

    cout << numbers[a] << '\n';
    

    to print the current element.


    Furthermore, if that's all your program is doing, then you don't actually need the array. All you need is a single int variable:

    int value;
    for (int a = 0; a < count; ++a)
    {
        InFile >> value;
        cout << value << '\n';
    }
    

    That also solve the problem with the variable-length array (since there isn't any).