gpt4 book ai didi

c++ - 对文件中的字符串进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:28 25 4
gpt4 key购买 nike

我需要一个基于姓氏使用 C++ 对 unix pwd 文件进行排序的解决方案。该文件的格式为用户名、密码、uid、gid、名称、homedir、shell。全部由冒号分隔符分隔。名称字段包含名字和姓氏,两者都用空格分隔我可以使用 map 对值进行排序,并且我正在发布我的代码。有人可以建议我改进我的代码吗?此外,我无法在我的文件中看到排序的行。

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;
}

}

此外,我在写入文件时遇到问题,我看不到排序结果。

我的问题:

    Can someone please explain me why I am unable to see the written results in the file!

感谢和问候,

老鼠。

最佳答案

由于文件的格式是固定的

username, password, uid, gid, first name(space)lastname, homedir, shell

维护一个 std::map 键值作为字符串(它将包含姓氏,值作为行号

开始逐行读取文件,提取姓氏(用“,”分隔行,然后在空格处分隔提取的第五部分)。

在 map 中存储名称和行号

读取完整文件后,只需输出 map 中提到的行号。 ( map 包含按排序顺序排列的纬度名称)

用于拆分字符串引用

Split a string in C++?

关于c++ - 对文件中的字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3155044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com