Hi, I am new to C++ and am getting stuck with just reading in data from a text file into an array. I have looked at lots of examples online, but can't find one that matches what I am trying to do.
The data consists of two variables, date and price, and looks like the following:
01/01/2010,37.58
01/02/2010,29.10
01/03/2010,24.59
01/04/2010,22.24
01/05/2010,32.90
.
.
.
For now, I am using just January data (31 records), but in general I will be using a file for a year (daily data), but with missing days.
I am attaching my code. My problem is that I am putting all of the first line into the string variable (first szTempDate and then pds.szDate). I don't know how to get it to read only the date and then how to get the price into pds.dPrice. I didn't put anything here to try to read the price because of the string problem. Also, if there is a simpler way to read the file into the array than what I have, I would love to know how.
My second question has to do with not knowing in general how many records are in the file without looking at it and I have to do this for a lot of years. Is there a way to create an array that has only the number of objects that correspond to the number of data records in the file and then have the program tell me how many that is?
Thanks very much!!
// reading a text file
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//PriceData - Defines a class that stores the date and price data
class PriceData
{
public:
std::string szDate;
double dPrice; //contains the daily price
void setDate(std::string& str)
{
szDate = str;
}
void setPrice(double& p)
{
dPrice = p;
}
};
// Allocate 31 objects of class PriceData
PriceData pds[31];
// Creat temporary variables for holding the data as it is read from the file
string szTempDate;
double dTempPrice;
//displayData - This function outputs the indexed data set
void displayData(PriceData& pds)
{
cout << pds.szDate;
cout << " ";
cout << pds.dPrice;
cout << endl;
}
int main (int nArg, char* pszArgs[])
{
ifstream myfile ("Prices.txt");
if (myfile.is_open())
{
//while (!myfile.eof())
//{
for(int i = 0; i <31; i++)
{
getline(myfile,szTempDate);
pds[i].setDate(szTempDate);
displayData(pds[i]);
}
//}
myfile.close();
}
else cout << "Unable to open file";
system("PAUSE");
return 0;
//}
}