1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
//Lab2_Vector Names
/*
Stage 1:
Create a vector of strings of various names like Smith, Joseph ( last name first)
(about 10 is enough)
Initialize manually.
Next sort the list in reverse alphabetical order using a function to describe the sort in the
sort function from the **algorithm** library.
Stage 2:
Get the strings for the vector from a file ( remember that the input file must be a **resource**
in Visual Studio).
Sort it as above and then write back to same file so it is overwritten with the sorted data.
Extra Credit.
Change the input file to add a tab and then a score between 1 and 100.
Change the function that governs the vector sort to sort by the scores rather than names.
Output the sorted data back to the file so that the lines are properly sorted so the name of
the highest score is on top etc.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std;
bool sorting(string a, string b);//sort function
int main()
{
vector<string> name;
string filename="myfile.txt";
/*
name.push_back("Cefalo, Joseph 100");
name.push_back("Marin, Alexa 097");
name.push_back("Loftus, Jay 043");
name.push_back("Pehl, Kaila 025");
name.push_back("Cefalo, Dunkin 088");
name.push_back("Marin, Cody 054");
name.push_back("Bond, James 067");
name.push_back("Ketchum, Ash 071");
name.push_back("Kline, Stacey 006");
name.push_back("Rogers, Emily 016");
*/
ifstream fin;
fin.open(filename); //open read file
if(fin.fail())
{
cout << "Input File Not Opened." << endl;
exit(1);
}
string temp;
while(getline(fin, temp))
{
name.push_back(temp);
}
fin.close(); //end of read file
sort(name.begin(), name.end(), sorting); //sorting of vector
ofstream fout;
//string filename="finalfile.txt";
fout.open(filename); //open write file
if(fout.fail())
{
cout << "File Failed to Open." << endl;
exit(0);
}
for(unsigned int i=0; i<name.size(); i++)
{
if(i==name.size()-1)
fout << name[i];
else
fout << name[i] << endl;
}
fout.close(); //end of write file
fout << "-------------------" << endl;
fout << "Writing to File. Check 'finalfile.txt' for Completion";
return 0;
}
bool sorting(string a, string b)//Sorting
{
a=a.substr(a.find('\t')); //find tab and make substring
int y=atoi(a.c_str()); //output as c-string
b=b.substr(b.find('\t'));//find tab and make substring
int z=atoi(b.c_str());//output as c-string
return y>z;
}
|