0

My ifstream is not reading integers correctly. My main is as follows:

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

int main() {

    vector<int> myvec;

    Tree myAVL;

    ifstream myfile;
    string filename;

    cout << "Enter the file name you would like to use: ";
    cin >> filename;

    myfile.open(filename);

    while (!myfile) {
        cout << "ERROR: INVALID FILENAME -- Please input valid filename: ";
        cin >> filename;
        myfile.open(filename);
    }

    while (!myfile.eof()) {
        int x;
        myfile >> x;

        if (myvec.size() == 0) {
            myvec.push_back(x);
            myAVL.insert(x);
            continue;
        }

        if (checkVecDuplicate(myvec, x))
        {
            myAVL.insert(x);
            myvec.push_back(x);
        }
    }

    for (int i = 0; i < myvec.size(); i++)
    {
        cout << myvec[i];
    }

    cout << endl << endl;

    Node* temp = myAVL.head;

    myAVL.inorder(temp);
    cout << endl << endl;
    myAVL.preorder(temp);
    cout << endl << endl;

    system("pause");

    return 0;
}

My text file I'm trying to read in is:

14
32
64
55
1
12
3
4
16
72
125
54

Why is this not reading any of the integers? At myfile >> x it's reading in a null value for the integer and I have no clue why. Thank you!

Azeem
  • 11,148
  • 4
  • 27
  • 40
  • 1
    Why are we seeing all of this unnecessary code with Nodes and avl trees to demonstrate the issue with reading integers? Please post a [mcve] – PaulMcKenzie Oct 26 '17 at 03:33
  • And please tell us what you mean by "null value". Do you mean *zero*? Also tell us the expected *and* actual output. – Some programmer dude Oct 26 '17 at 03:35
  • 2
    [why `while (!myfile.eof())` is wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Barmar Oct 26 '17 at 03:36
  • Also take some time to 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) And [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert. – Some programmer dude Oct 26 '17 at 03:36
  • Expected is that it at least reads in 14, but visual studio is outputting -858993460 which looks like the memory has been initialized, but it stays as that value for each integer – user3277528 Oct 26 '17 at 03:41
  • Possible duplicate of [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user0042 Oct 26 '17 at 03:47

0 Answers0