我正在创建一个系统,输出我的一个文本文件中的所有注册学生,例如
123 Michael
412 Voker
512 Karl
143 Riki
我需要使用他们的ID来搜索学生意味着我需要阅读这个注册学生档案。
系统只会询问身份证。例如
Type ID num: 123
OUTPUT:
Hello Michael your ID number is 123.
可能你正在寻找一个结构或类。我会说,做一个学生班。
class Student{
public:
int id;
char *name;
};
Student s;
通过链接[1]来了解如何分别从文件读取或写入学生对象。
[1] https://www.geeksforgeeks.org/readwrite-class-objects-fromto-file-c/
等等,在这里我编写了一个包含所有发布问题的工作示例。
下面的解决方案是用非常惯用的c++
方式编写的(该解决方案在编写/读取非平凡容器数据类型的文件时使用stream_iterators
(即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 $