I would like to know whether the following code can be changed in any way as to improve its functionality. Could there be any potential bugs that may arise as a result of how the code is written?
The program is designed to find the total volume traded for each stock and to also find the high and low for each of those stocks.
Are there any lines of code that are poorly written? Either syntactical or just a better way to express the logic.
#include <cstdio>
#include <cstring>
#include <map>
#include <iostream>
#include <string>
using namespace std;
typedef basic_string<char> string;
class CHighLow
{
public:
CHighLow() : nCurLow(0), nCurHigh(0) {};
void add(int nHigh, int nLow)
{
if (nHigh > nCurHigh)
nCurHigh = nHigh;
if (nLow < nCurLow)
nCurLow = nLow;
}
int& getSum()
{
int sum = nCurLow + nCurHigh;
return sum;
}
int nCurLow;
int nCurHigh;
};
int main(int argc, char* argv[])
{
if (!strcmp("version", argv[1]))
{
cerr << "Using version 1.0 VWAPer" << endl;
return 0;
}
FILE* file = fopen(argv[2], "r");
cerr << "Reading file" << argv[2] << endl;
char line[256];
char Stocks[1000][10];
int Intervals[1000];
int Volumes[1000];
float Highs[1000];
float Lows[1000];
int i = 0;
int sum = 0;
while (fgets(line, 256, file))
{
sscanf(line, "%s %d %d %f %f",
Stocks[i], &Intervals[i],
&Volumes[i], &Highs[i], &Lows[i++]);
}
cerr << "Calculating total volumes" << endl;
Map<std::string, int> TotalVolumes;
for (int s = 0; s <= I; ++s)
{
std::string stockname = Stocks[s];
for (int j =0; j <= i; ++j)
{
if (!strcmp(Stocks[j], stockname.c_str()))
{
TotalVolumes[stockname] += Volumes[j];
}
}
}
cerr << "Calculating high lows" << endl;
map<std::string, CHighLow> HighLows;
for (int s = 0; s <= i; ++s)
{
HighLows[Stocks[s]].add(Highs[s], Lows[s]);
cout << HighLows[Stocks[s]].getSum();
}
cerr << "Writing files" << endl;
for (int s = 0; s <= i; ++s)
{
cout << Stocks[s] << "," << Intervals[s] << "," <<
TotalVolumes[Stocks[s]] / Volumes[s] * 100 << endl;
}
map<std::string, CHighLow>::iterator itr = HighLows.begin();
while (itr != HighLows.end())
{
cout << (*itr).first << "," << (*itr).second.nCurLow << "," <<
(*itr).second.nCurHigh << endl;
++itr;
}
return 1;
}