I'm needing to make a little program that can read in data from a .txt file, put that data into a list, sort that list, and then display in descending order. I'm good to go on sorting the list and displaying in descending order, but I'm having trouble figuring out how to read in data from an external file and then put that data in a list. Any help would be greatly appreciated.
Considering you havee all the sorting down, im assuming youre using an array class you made or a vector class so lets get to the input file.
#include<iostream>
#include <string>
#include<fstream>//open / close files
#include<vector>//if you want to store your list this way
#include<algorithm>//if you want to use for sorting and other algorithms
using namespace std;
int main()
{
ifstream infile;
infile.open("yourfile.txt");//open your file
if(!infile)//check to make sure its open before trying to initialize list items
{
std::cout<<"\nUnable to open file!\n";
return 0;
}
vector<string> list;//create your empty list
while(!infile.eof())//while the input stream has not reached the end of your file
{
string temp = "";//create a temporary string
for(int i = 0; i < sizeof(list.max_size()); i++)
{
infile >> temp;//grab the input
list.push_back(temp);//put it in the next available list slot
++i;
}
}
//sort before entering this loop for output
for(int i = 0; i < (int)list.size(); i++)
{
cout << list[i] << endl;//test list for proper assignments
}
system("pause");
infile.close();
return 0;
}