Reading in file to an array thats part of a class

Hello all,

I need to read in a file with floats into an array that is initialized as part of a class. I know this is very basic and short code but I cannot get it to read the file (or print it out) and at this point I have no idea what I'm doing wrong. Please point me in the right direction. Code is as follows (I don't know how to post my code like I've seen people do on this site).

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

const int MAX_LENGTH = 50;
class FloatList

{
public:
void getList(ifstream&);
void printList() const;

FloatList();
~FloatList();

private:
int length;
float values[MAX_LENGTH];

};

int main()
{
ifstream tempData;
float temp = 0.0;

FloatList list;

cout << fixed << showpoint;
cout << setprecision(2);

tempData.open("temperatures.txt");

if (!tempData)
{
cout << "File did not open\n";
}

list.getList(tempData);
list.printList();

return 0;
}



FloatList::FloatList()
{
length = 0;
}

void FloatList::getList(ifstream &List)
{
while (!List.eof() && length < MAX_LENGTH)
{
List >> values[length];
length++;
}
}

void FloatList::printList() const
{
for (int count = 0; count == length; count++)
{
cout << values[count];
}
}

FloatList::~FloatList()
{
cout << "The destructor has been invoked\n";
}


Hi,

Code Tags:

http://www.cplusplus.com/articles/z13hAqkS/

First up, prefer double rather than float, the latter precision is easily exceeded. Try to avoid putting the name of types into function names, if the type changes, one has to change all the function names.

Don't loop on eof, it's too late by then :+) instead loop on the read operation:


1
2
3
4
5
void FloatList::getList(ifstream &List)
{
   length = 0;
   while (List >> values[length] && length < MAX_LENGTH) {length++;}
}


A for loop looks like this:

1
2
for (int count = 0; count < length; ++count)  // the middle expression ends the loop when it becomes false
{



A slightly fancier and much safer way is to use a range based for loop:

1
2
3
4
for (const auto& item : values) { // item is a value in the array
    std::cout << item << " "; // with spaces 
}
 std::cout << "\n";


This might be too advanced right now but there you go :+)

The const means we are not going to change the value of an item. auto automatically detects the type of the item. The & isn't really necessary here - it means that each item is a reference (another name for a variable, kind of like a pointer), there is not a lot of point doing that for an int, so it could be left out here.

constexpr is stronger than const, it's const'ness can't be cast away, so:

constexpr int MAX_LENGTH = 50;

But one should try to avoid global variables.

Good Luck !!



Last edited on
Thank you for your help!
Topic archived. No new replies allowed.