Quote:
Originally Posted by Drowzee C doesn't explicitly support vectors, right? Otherwise, why bother using malloc at all? |
No, C doesn't have vectors, which can make this problem a little easier. That's why I asked up front in regard to the design.
[edit]So sticking with that...
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cstdio>
struct sRecord
{
int date, volume;
char time[8];
double price[4];
};
bool operator< (const struct sRecord &a, const struct sRecord &b)
{
return a.volume < b.volume;
}
std::ostream& operator<< (std::ostream &o, struct sRecord &r)
{
return o << r.date << ","
<< r.time << ","
<< r.price[0] << ","
<< r.price[1] << ","
<< r.price[2] << ","
<< r.price[3] << ","
<< r.volume;
}
int main(void)
{
std::vector<sRecord> record;
const std::string filename("file.csv");
std::ifstream file(filename.c_str());
if ( file )
{
std::string line;
while ( file >> line )
{
sRecord data;
if ( std::sscanf(line.c_str(), "%d,%7[^,],%lf,%lf,%lf,%lf,%d",
&data.date, &data.time, &data.price[0], &data.price[1],
&data.price[2], &data.price[3], &data.volume) == 7 )
{
record.push_back(data);
}
}
}
/*
* [Modify contents]
*/
std::sort(record.begin(), record.end());
std::copy(record.begin(), record.end(),
std::ostream_iterator<sRecord>(std::cout, "\n"));
return 0;
}
/* file.csv
20041201,0:00,102.74,102.77,102.74,102.76,5
20041201,0:05,102.78,102.78,102.75,102.75,3
20041201,0:10,102.75,102.75,102.7,102.7,7
20041201,0:15,102.7,102.72,102.7,102.72,8
20041201,0:20,102.73,102.74,102.73,102.74,2
20041201,0:25,102.73,102.73,102.7,102.7,4
20041201,0:30,102.71,102.71,102.68,102.7,10
20041201,0:35,102.71,102.73,102.68,102.69,15
20041201,0:40,102.7,102.71,102.69,102.71,12
20041201,0:45,102.71,102.73,102.71,102.73,2
20041201,0:50,102.74,102.78,102.74,102.77,12
20041201,0:55,102.77,102.8,102.77,102.79,17
*/
/* my output
20041201,0:20,102.73,102.74,102.73,102.74,2
20041201,0:45,102.71,102.73,102.71,102.73,2
20041201,0:05,102.78,102.78,102.75,102.75,3
20041201,0:25,102.73,102.73,102.7,102.7,4
20041201,0:00,102.74,102.77,102.74,102.76,5
20041201,0:10,102.75,102.75,102.7,102.7,7
20041201,0:15,102.7,102.72,102.7,102.72,8
20041201,0:30,102.71,102.71,102.68,102.7,10
20041201,0:40,102.7,102.71,102.69,102.71,12
20041201,0:50,102.74,102.78,102.74,102.77,12
20041201,0:35,102.71,102.73,102.68,102.69,15
20041201,0:55,102.77,102.8,102.77,102.79,17
*/
I didn't know what to sort by, so I chose volume.