如何使用ID搜索记录 [英] How to search record using an id
问题描述
我正在创建一个系统,该系统在我的一个文本文件中输出所有注册的学生,例如
I am creating the system that outputs all the registered student in one of my textfile e.g
123 Michael
412 Voker
512 Karl
143 Riki
我需要使用他们的ID来搜索学生 意味着我需要阅读此注册学生文件.
I need to use their ID to search for the student Means i need to read this register student file.
系统仅询问ID. 例如
The system will only ask for the ID. e.g
Type ID num: 123
输出:
Hello Michael your ID number is 123.
推荐答案
请继续,这里我编译了一个工作示例,涵盖了您发布的所有问题.
Hang on, here I have compiled a working example covering all your posted questions.
尽管以下解决方案是以非常惯用的c++
方式编写的(在为非平凡的容器数据类型(例如std::map
)编写/读取文件时,该解决方案使用stream_iterators
的用法:
The below solution though is written in a very idiomatic c++
way (the solution sports a usage of stream_iterators
when writing/reading files for a non-trivial container data type (i.e. std::map
):
#include <iostream>
#include <map>
#include <sstream>
#include <algorithm> // copy, ...
#include <utility> // pair, ...
#include <fstream>
#include <iterator>
using namespace std;
typedef map<size_t, string> directory;
typedef pair<size_t, string> dir_kv_pair;
struct kv_dir : public dir_kv_pair {
kv_dir(void) = default;
kv_dir(directory::value_type kv): // type conversion helper
dir_kv_pair{kv} {} // pair <-> kv_dir
friend ostream & operator<<(ostream & os, const kv_dir &kv)
{ return os << kv.first << " " << kv.second << endl; }
friend istream & operator>>(istream & is, kv_dir& kv) {
if((is >> kv.second).eof()) return is;
kv.first = stol(kv.second);
return is >> kv.second;
}
};
int main()
{
string fname = "dir.txt";
{ // write into file
directory dir;
// filling the container
dir[123] = "Michael";
dir[412] = "Voker";
dir[512] = "Karl";
dir[143] = "Riki";
// writing to file:
ofstream fout{fname};
copy(dir.begin(), dir.end(), ostream_iterator<kv_dir> {fout});
}
// reading from file:
directory dir{ istream_iterator<kv_dir>{ ifstream{fname} >> skipws },
istream_iterator<kv_dir>{} };
// finding by ID
size_t id = 512;
cout << "Pupil id [" << id << "]: " << (dir.count(id) == 1? dir[id]: "not found") << endl;
}
示例输出:
Pupil id [512]: Karl
bash $
bash $ cat dir.txt
123 Michael
143 Riki
412 Voker
512 Karl
bash $
这篇关于如何使用ID搜索记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!