question

according to the following simple task:
Write a c++ class called 'student' with
Data members:
name(char type),
marks1,marks2 (integer type)
The program asks the user to enter name and marks. Then calcMedia()
calculates the media note and disp() display name and total media mark on
the screen in different lines.
Below is the given solution, however, it does not compile. Would like to see a different approach to the solution provided if possible.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>

using namespace std;

class Student{
public:

    char *name;
    int mark1; 
    int mark2;

    Student(char* na, int ma1, int ma2) {
        name = na;
        mark1 = ma1;
        mark2 = ma2;
    }

    int calc_media() {
        return (mark1 + mark2) / 2;
    }

    void disp() {
        cout << "Student:" << name << " \n media:"<< calc_media() <<"\n";
    }
};
 
int main()
{
    char* nam;
    int m1,m2;

    cout << "Enter name:";
    cin>> nam;

    cout << "Enter marks of two subjects:";
    cin>> m1;
    cin>> m2;

    Student student1(nam, m1, m2);

    student1.disp();
    return 0;
}

Last edited on
It compiles fine, though does emit a warning:
 In function 'int main()':
33:14: warning: 'nam' is used uninitialized in this function [-Wuninitialized]

What actually most likely mean is that your program has run-time errors.

Your first issue is that you are trying to put user input into an invalid pointer (nam).

name(char type),
If that is what your text says, then you should be using char, not char*. But that only allows you to enter one character, not a string. I assume you wrote it down wrong, and your assignment does want you to use c-strings, which is unfortunate.

Anyway, an easy fix would be to change it so that you have an actual char array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
int main()
{
    const int MaxLength = 1024;
    char nam[MaxLength] = {};
    
    int m1, m2;

    cout << "Enter name:";
    cin >> nam;

    cout << "Enter marks of two subjects:";
    cin >> m1;
    cin >> m2;

    Student student1(nam, m1, m2);

    student1.disp();
    return 0;
}
Last edited on
Thank you for your reply
Topic archived. No new replies allowed.