For my lab, the user is supposed to input a filename. That file prints out the date and price and then my code is supposed to find the highest and lowest prices and print those out with their corresponding dates. I feel like the logic in my code makes sense but it's not working.
//Todo: declare your functions here.
int main()
{
ifstream infile;
string fileName;
cout <<"Enter the name of the file to be analyzed:";
cin >> fileName;
// TODO: Open the filename and test that it was successful
infile.open(fileName);
// Used to read in the date, price and the rest.
double price = 0;
string date, junk;
// Going to store the date of the high price and low price
string lowDate, highDate;
// Going to store the high price and low price.
double high = -9999999;
double low = 99999;
cout.precision(2);
cout.setf(ios::fixed);
if(infile.is_open() == false)// problem opening the file? Maybe it does not exist
cout << "File " << fileName << " cannot be opened.";
// TODO: Implement a loop that reads line by line from input.
// TODO: A line has the date, the price and the rest (use junk)
// TODO: Stop reading on end of input.
while ( infile >> date >> price >> junk ) // treat infile like 'cin'
{
cout << date << " " << price << endl;
// TODO: Find the highest price
// TODO: Save the date of the price
// TODO: Find the lowest price
// TODO: Save the date of the price
if (price > high)
{
price = high;
date = highDate;
}
else if (price < low)
{
price = low;
date = lowDate;
break;
}
cout << "High: " << high << " on " << highDate << endl;
cout << "Low: " << low << " on " << lowDate << endl;
}
infile.close();
}
P.S. I know the last two cout statements to print the highest and lowest prices should be outside of the while loop, but when I do that it still outputs the statements if the file fails to open which is not what's supposed to happen so I also don't know what to do about that.
// TODO: Open the filename and test that it was successful
infile.open(fileName);
So where is your test? If the file did not open you still continue with the program.
Found the test at line 24, but it is to late and the program still continues if the file did not open
Try this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
ifstream infile;
string fileName;
cout << "Enter the name of the file to be analyzed:";
std::getline(std::cin, fileName); // <--- Because the file name may contain a space.
// TODO: Open the filename and test that it was successful
infile.open(fileName);
ifI(!infile)
{
std::cout << "\n File \"" << fileName << "\" did not open!\n";
return 1; // <--- Leave the program because there is no point in continuing.
}
With out seeing the input file, or a fair sample, it is hard to say if you are reading the file correctly to start with.