我有一个txt文件,其中包含名称,id号,mobilenumber和以逗号分隔的行的位置。

罗比,7890,7788992356,123威斯敏斯特
汤姆,金士顿路124号8820,77882345
我的任务是取回

通过姓名查找员工的所有信息。
通过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;
}

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

09-10 03:50
查看更多