Search code examples
c++fileiofstream

Function in a class that doesn't take a variable. but reads/prints an array


So I have a class:

class myClass {
public:
    void readFile();

private:
    int sPerDay[10];

};

And I want this function to read/print the array of the text file (a bunch of numbers 10 lines long)

void myClass::readFile()
{

    ifstream read("numbers.txt");
    for(int i=0;i<10;i++)
        read>>sPerDay[i];

    for (int i = 0;i<10;i++) {
        cout << sPerDay[i];
    }
}

Output is a bunch of random numbers. Where am I going wrong?


Solution

  • If you are not sure whether the file exists, or whether it is in the same directory as your executable, modify your code to check if the file opened, like this for example:

    void readFile() {
        ifstream read("numbersd.txt");
        if(!read) { cerr << "File didn't open..Does it exist?" << endl; return; }
        ...
    

    Then, if it didn't open, here are some things that might be happening:

    1. File doesn't exist.
    2. File is not in the path you think it is.
    3. You don't have the rights to access that file.

    The problem lies in the file, since the code works fine, given that the file numbers.txt exists (and it's in the same directory with your executable file) I used that one for example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    and the result is:

    C02QT2UBFVH6-lm:~ gsamaras$ g++ main.cpp
    C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
    1 2 3 4 5 6 7 8 9 10 
    

    And this is the code I used from you:

    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    class myClass {
    public:
        void readFile() {
            ifstream read("numbers.txt");
            for(int i=0;i<10;i++)
               read>>sPerDay[i];
    
            for (int i = 0;i<10;i++) {
               cout << sPerDay[i] << " ";
            }
           cout << "\n";
        }
    
    private:
        int sPerDay[10];
    
    };
    
    
    int main() {
        myClass obj;
        obj.readFile();
        return 0;
    }