File tree Expand file tree Collapse file tree 3 files changed +16
-4
lines changed Expand file tree Collapse file tree 3 files changed +16
-4
lines changed Original file line number Diff line number Diff line change @@ -26,9 +26,12 @@ int main(int argc, char **argv) {
26
26
ifile->open (" student.dat" , std::ios::binary);
27
27
if (ifile->is_open ()) {
28
28
Student *s = new Student ();
29
+
30
+ // safely read file from the
31
+ ifile->read (reinterpret_cast <char *>(s), sizeof (Student));
29
32
while (!ifile->eof ()) {
30
- ifile->read (reinterpret_cast <char *>(s), sizeof (Student));
31
33
std::cout << s->whoami () << std::endl;
34
+ ifile->read (reinterpret_cast <char *>(s), sizeof (Student));
32
35
}
33
36
} else {
34
37
std::cerr << " Unable to open file\n " ;
Original file line number Diff line number Diff line change 1
1
#include " student.hpp"
2
+ #include < cstring>
2
3
#include < sstream>
3
4
#include < string>
4
5
5
6
void Student::setAge (int age) { this ->age = age; }
6
7
void Student::setAge (short age) { this ->age = age; }
7
8
void Student::setAge (unsigned short age) { this ->age = age; }
8
9
9
- void Student::setName (std::string &name) { this ->name = name; }
10
- void Student::setName (const char *name) { this ->name = std::string (name); }
10
+ void Student::setName (std::string &name) {
11
+ if (name.length () < 50 ) {
12
+ std::strcpy (this ->name , name.c_str ());
13
+ }
14
+ }
15
+ void Student::setName (const char *name) {
16
+ if (std::strlen (name) < 50 ) {
17
+ std::strcpy (this ->name , name);
18
+ }
19
+ }
11
20
12
21
std::string Student::whoami () const {
13
22
std::stringstream s;
Original file line number Diff line number Diff line change 2
2
3
3
class Student {
4
4
private:
5
- std::string name;
5
+ char name[ 50 ] ;
6
6
unsigned short age;
7
7
8
8
public:
You can’t perform that action at this time.
0 commit comments