0

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?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Andrew
  • 29
  • 1
  • 1
  • 7

2 Answers2

0

You could be doing many things wrong.

1) The file numbers.txt does not exist, and this code fails to check that the file was successfully opened.

2) The file numbers.txt exists, but does not contain ten integer numbers, separated by whitespace, and this code fails to check whether operator>> succeeded, or not.

3) This code also prints ten numbers to std::cout without any separating character. At best, the output you will get is what looks line one large number.

So, there are at least two or three things that are wrong here. You need to fix all of them:

A) Verify that the file has been opened succesfully.

B) After every operator>> invocation, check if the file stream is good(), or not.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

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;
}
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305