Reading data from file into an array

Hi I have compiled your code, with the .txt it runs well, without gives the strage numbers that you see. So probably you are opening a file that does not exists, or can not be red.

// This program reads data from a file into an array.

#include <iostream>
#include <fstream> // To use ifstream
#include <vector>
using namespace std;

int main()
    std::vector<int> numbers;
    ifstream inputFile("c.txt");        // Input file stream object

    // Check if exists and then open the file.
    if (inputFile.good()) {
        // Push items into a vector
        int current_number = 0;
        while (inputFile >> current_number){

        // Close the file.

        // Display the numbers read:
        cout << "The numbers are: ";
        for (int count = 0; count < numbers.size(); count++){
            cout << numbers[count] << " ";

        cout << endl;
    }else {
        cout << "Error!";

    return 0;

This snippet checks if the file exists, raises an error if not, and uses a vector(more suitable in c++)

Leave a Comment