I have this .txt file. I want to extract each element that is separated by a space. For example, in line one I want to be able to extract "41" "63" as separate tokens to make a bar chart using *. The asterisk would represent the difference between the low to high temperature.
#include <iostream> // <--- You forgot this 1.
#include <iomanip>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
string line;
ifstream temp_file;
int months{};
int lowTemp{},highTemp{}; // <--- Added.
temp_file.open("temperature.txt");
// <--- How do you know it is open and ready to use?if (!temp_file) // <--- Added.
{
std::cerr << "\n File \"temperature.txt\" did not open\n";
return 1;
}
while (temp_file >> lowTemp >> highTemp) // <--- Changed.
//while (getline(temp_file, line))
{
//months++; // <--- Changed.
//cout << months << right << setw(30) << line << "\n" << endl;
cout << setw(2) << months++ << setw(4) << lowTemp << " " << setw(4) << highTemp << " Difference is: " << highTemp - lowTemp << "\n";
}
//temp_file.close(); // <--- Not required as the dtor will close the file when the function looses scope.
return 0; // <--- Not required, but makes a good break point for testing.
}
This produces this output:
0 41 63 Difference is: 22
1 46 67 Difference is: 21
2 53 75 Difference is: 22
3 59 81 Difference is: 22
4 67 87 Difference is: 20
5 74 94 Difference is: 20
6 76 98 Difference is: 22
7 76 100 Difference is: 24
8 72 93 Difference is: 21
9 61 83 Difference is: 22
10 50 72 Difference is: 22
11 44 64 Difference is: 20
This should give you some ideas of where to go from hers.