user2905256
user2905256

Reputation: 145

C++ Getting values from file into array

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>

using namespace std;

void make_array(ifstream& num, int (&array)[50]);

int main()
{
    ifstream file; // variable controlling the file
    char filename[100]; /// to handle calling the file name;
    int array[50];

    cout << "Please enter the name of the file you wish to process:";
    cin >> filename;
    cout << "\n";

    file.open(filename);

    if (file.fail()) {
        cout << "The file failed to open.\n";
        exit(1);
    } else {
        cout << "File Opened Successfully.\n";
    }

    make_array(file, array);

    file.close();

    return (0);
}

void make_array(ifstream& num, int (&array)[50])
{
    int i = 0; // counter variable

    while (!num.eof() && i < 50) {
        num >> array[i];
        i = i + 1;
    }

    for (i; i >= 0; i--) {
        cout << array[i] << "\n";
    }
}

I am trying to read values from a file to an array using fstream. When I try to display the contents of the array, I get 2 really big negative numbers, and then the contents of the file.

Any ideas what I did wrong?

Upvotes: 0

Views: 185

Answers (2)

leemes
leemes

Reputation: 45725

As discussed in the comments, you try to read an integer which is encoded as text. For this, you need to use operator>> (which reads any type encoded as string) instead of get (which reads a single byte):

num >> array[i];

Upvotes: 0

Carey Gregory
Carey Gregory

Reputation: 6846

Your use of num.get(array[i]) doesn't match any of its signatures. See get method description. What you want is this:

array[i] = num.get();

Upvotes: 1

Related Questions