I need a solution for sorting of unix pwd file using C++ based on the last name. The format of the file is username, password, uid, gid, name, homedir, shell. All are seperated by colon delimiters. The name field contains first name follwed by last name both seperated by space I am able to sort the values using map and i am posting my code. Can some one suggest me improvements that I can do to my code please. Also I am unable to see the sorted lines in my file.
string line,item;
fstream myfile("pwd.txt");
vector<string> lines;
map<string,int> lastNames;
map<string,int>::iterator it;
if(myfile.is_open())
{
char delim =':';
int count =0;
while(!myfile.eof())
{
count++;
vector<string> tokens;
getline(myfile,line);
istringstream iss(line);
lines.push_back(line);
while(getline(iss,item,delim))
{
tokens.push_back(item);
}
cout<<tokens.size()<<endl;;
size_t i =tokens[4].find(" ");
string temp = tokens[4].substr(i,(tokens[4].size()-i));
cout<<temp<<endl;
lastNames.insert(pair<string,int>(temp,count));
tokens.clear();
}
myfile.seekg(0,ios::beg);
for(it=lastNames.begin();it!=lastNames.end();it++)
{
cout << (*it).first << " => " << (*it).second << endl;
int value=lastNames[(*it).first ];
myfile<<lines[value-1]<<endl;
cout<<lines[value-1]<<endl;
cout<<value<<endl;
}
}
Also I am having problem writing to the file I am unable to see the sorted results.
my problem:
Can someone please explain me why I am unable to see the written results in the file!
Thanks & Regards,
Mousey.
Since the format of the file is fixed
Maintain a std::map with key value as string (which will contain last name, and value as line number
Start reading the file line by line, extract the last name (Split the line by “,” and then split fifth extracted part on space).
Store the name along with line number in map
When complete file has been read, just output the line numbers as mentioned in map. (Map contains lat names in sorted order)
For splitting a string
Refer to
Split a string in C++?