gpt4 book ai didi

c++ - 如何使用 C++ STL 作业操作 txt 文件

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:49 26 4
gpt4 key购买 nike

我有一个 txt 文件,其中包含姓名、身份证号码、手机号码和以逗号分隔的位置。例子 罗比,7890,7788992356, 123 westminister 汤姆, 8820, 77882345, 金士顿路 124 号我的任务是找回

按姓名查找员工的所有信息。通过 ID 查找员工的所有信息。添加员工信息。更新员工信息。

到目前为止,我已经读取了文件并将信息存储在 vector 中。代码如下所示。对于任务1)按姓名查找员工的所有信息。我将在 vector 中迭代并打印包含名称的信息。我将能够做到2) 文本文件中的simialry 我将查找id 并打印有关它的信息。但是我对第 3 点和第 4 点一无所知。

我在下面发布我的代码

void filter_text( vector<string> *words, string name)    
{
vector<string>::iterator startIt = words->begin();
vector<string>::iterator endIt = words->end();
if( !name.size() )
std::cout << " no word to found for empty string ";

while( startIt != endIt)
{
string::size_type pos = 0;
while( (pos = (*startIt).find_first_of(name, pos) ) != string::npos)
std:cout <<" the name is " << *startIt<< end;
startIt++;
}
}

int main()
{
// to read a text file
std::string file_name;
std::cout << " please enter the file name to parse" ;
std::cin >> file_name;

//open text file for input
ifstream infile(file_name.c_str(), ios::in) ;
if(! infile)
{
std::cerr <<" failed to open file\n";
exit(-1);
}
vector<string> *lines_of_text = new vector<string>;
string textline;
while(getline(infile, textline, '\n'))
{
std::cout <<" line text:" << textline <<std::endl;
lines_of_text->push_back(textline);
}
filter_text( lines_of_text, "tony");
return 0;
}

最佳答案

#include <string>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <fstream>

struct bird {
std::string name;
int weight;
int height;
};

bird& find_bird_by_name(std::vector<bird>& birds, const std::string& name) {
for(unsigned int i=0; i<birds.size(); ++i) {
if (birds[i].name == name)
return birds[i];
}
throw std::runtime_error("BIRD NOT FOUND");
}

bird& find_bird_by_weight(std::vector<bird>& birds, int weight) {
for(unsigned int i=0; i<birds.size(); ++i) {
if (birds[i].weight< weight)
return birds[i];
}
throw std::runtime_error("BIRD NOT FOUND");
}

int main() {
std::ifstream infile("birds.txt");
char comma;
bird newbird;
std::vector<bird> birds;
//load in all the birds
while (infile >> newbird.name >> comma >> newbird.weight >> comma >> newbird.height)
birds.push_back(newbird);
//find bird by name
bird& namebird = find_bird_by_name(birds, "Crow");
std::cout << "found " << namebird.name << '\n';
//find bird by weight
bird& weightbird = find_bird_by_weight(birds, 10);
std::cout << "found " << weightbird.name << '\n';
//add a bird
std::cout << "Bird name: ";
std::cin >> newbird.name;
std::cout << "Bird weight: ";
std::cin >> newbird.weight;
std::cout << "Bird height: ";
std::cin >> newbird.height;
birds.push_back(newbird);
//update a bird
bird& editbird = find_bird_by_name(birds, "Raven");
editbird.weight = 1000000;

return 0;
}

显然不是员工,因为那样会使您的家庭作业变得太容易。

关于c++ - 如何使用 C++ STL 作业操作 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7748004/

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