I have to sort an input file using lists. How do i make an input file into a list. Do i have to store it in a vector first?
The input file has 100 words in random order
#include <iostream>
#include <list>
#include <fstream> // ifstream and ofstream
#include <string> // string
#include <vector> // For later, when you add a vector
#include <algorithm>
// You may want to add this in later, when you add a vector so that you can use the sort in algorithm
void readFile(std::string, std::vector<std::string>, std::ifstream);
int main()
{
std::list <int> data;
std::string Input_File;
std::string Output_File;
std::vector<std::string> vectdata;
std::string line;
std::ifstream Num_Rec_File;
std::ofstream Num_Rec_Output;
std::cout << "Please enter the name of the input file";
std::cin >> Input_File;
std::cout << "\nPlease enter the name of the output file for these data:\n";
std::cin >> Output_File;
Num_Rec_File.open(Input_File);
if (Num_Rec_File.fail())
{
std::cout << "\n" << Input_File << " was not able to be opened for reading\n";
return 1;
}
else
{
std::cout << "\n" << Input_File << " was opened for reading\n";
}
Num_Rec_Output.open(Output_File);
if (Num_Rec_Output.fail())
{
std::cout << "\n" << Output_File << " was not able to be opened for reading\n";
return 1;
}
else
{
std::cout << "\n" << Output_File << " was opened for reading\n";
}
//readFile(Input_File, vectdata, Num_Rec_File);
std::list <int> alist;
std::list <int>::iterator iter; //l_iter is the list iterator (basically an internal pointer)
int ivalue;
// Set l_iter to beginning
iter = alist.begin();
while (std::cin.good()) // changed loop slightly, will continue to go until non integer intered
{
alist.insert(iter, ivalue); // inserts at the beginning
// Note that this also would work: alist.insert(alist.begin(), ivalue);
//++iter; // This statement creates a run time error on some systems, as you advance the interator off the end of the list
iter = alist.end();
std::cin >> ivalue;
}
// sort the list
alist.sort(); // This is a sort that is part of the list class.
// print the list
std::cout << "\nSorted list: \n";
//for (iter = alist.begin(); iter != alist.end(); ++iter) - conventional for loop
for (int i:alist) // Note that this range based for is new in C++11. It won't work on the prior versions.
{
//std::cout << *iter << std::endl; // This uses the pointer to print the values in the list --- conventional loop
std::cout << i << std::endl; // using the range based index
}
return 0;
}
Your code doesn't match the description. If your input file has words why do you want to store ints ?
Anyway, to read and sort the words is actually very easy.