我如何从文件中搜索一个人的全名和其他信息



!它会在文件中打印第一个人的全名,但我该如何制作它,以便在我将此人的全名写入控制台时,代码会打印所有信息。

这是我的搜索函数代码。



while (std::getline(in_out_file, lines))
{
my_vec.push_back(lines); 

}

for(int i = 0;i < my_vec.size(); ++i){
if(search == my_vec[i]){
std::cout << search << std::endl;
std::cout << "Match found" << std::endl;
break;
//           std::cout << "ntThe fullname is     :    " << info.full_name; 
//  std::cout << "ntThe address  is     :    " << info.address; 
//  std::cout << "ntThe E-post is       :    " << info.e_post; 
//  std::cout << "ntThe number is       :    " << info.phone_num; 
//  std::cout << "ntThe birthday is     :    " << info.birth_date; 
//  std::cout << "ntAnything else       :    " << info.anything_else; 
} else {
std::cout << "Match not found "<< std::endl;
break;
}
} 
in_out_file.close();
return 0;
}

Hello这里是一个工作示例。程序的健壮性取决于如何检查行的内容与用户搜索模式。在这里,我删除了搜索模式中的所有空格一行进行匹配。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <fstream>
#include <map>
using namespace std;
std::string embedded_test_file = R"(Tom Cruise 
Los Angelse Manchester Street 234 1223
tom@gmail.com
0354221112
23 July
Mission Accomplished
Jordan Jordansson
Georga computerStreet 12 34567
jordan@gmail.com
032456789
20 January
My new book is coming soon)";
struct searching_contact
{
std::string full_name{""};
std::string address{""};
std::string e_post{""};
std::string phone_num{""};
std::string birth_date{""};
std::string anything_else{""};
std::string new_line{""};
};
string remove_white_space(const string &var)
{
string res;
for (const auto &c:var)
{
if (c != ' ') {res.push_back(c);}
}
return res;
}

int search_contact()
{
searching_contact info;
std::stringstream in_out_file{embedded_test_file};
std::string search{};

std::vector<std::string> lines;
bool found = false;
std::cout << "Enter Key to search: ";
std::getline(std::cin, search);

std::string line;
while (std::getline(in_out_file, line))
{
lines.push_back(line);
}
auto search_no_space = remove_white_space(search);
for (int i = 0; i < lines.size(); ++i)
{
cout << "searching: "<< search <<" in <" <<lines[i] <<">" << endl;
auto line_no_space = remove_white_space(lines[i]);
if (search_no_space.compare(line_no_space) == 0)
{

std::cout << "Match found" << std::endl;
info.full_name = lines[i];
i++;
info.address = lines[i];
i++;
info.e_post = lines[i];
i++;
info.phone_num = lines[i];
i++;
info.birth_date = lines[i];
i++;
info.anything_else = lines[i];
i++;
info.new_line = lines[i];
i++;
found = true;
break;
}
}

return found == true ? 0 : -1;
}
int main(void)
{
return search_contact();
}

最新更新