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
I need to use their ID to search for the student
Means i need to read this register student file.
The system will only ask for the ID.
e.g
Type ID num: 123
OUTPUT:
Hello Michael your ID number is 123.
Probably your are looking for a struct or class.
Make a Student class I would say.
class Student{
public:
int id;
char *name;
};
Student s;
Give a go through the link [1] to understand how you can read or write a Student object from or to a file respectively.
[1] https://www.geeksforgeeks.org/readwrite-class-objects-fromto-file-c/
Hang on, here I have compiled a working example covering all your posted questions.
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;
}
Sample output:
Pupil id [512]: Karl
bash $
bash $ cat dir.txt
123 Michael
143 Riki
412 Voker
512 Karl
bash $