billy reynolds
billy reynolds

Reputation: 23

using method on member of struct from global function in C++

I'm very new to C++ and I'm always running into little things here and there. The most recent appears to be a problem with a struct.

struct student_record{
student_record(std::string name, int ident, double gpa){
    for (int i = 0; i < name.length(); i++){
        student_name[i] = name[i];
        student_name[i + 1] = NULL;
    }

    student_ident = ident;
    student_gpa = gpa;
}
//constructor to initialize student_record

static const unsigned int MAX_NAME_LENGTH = 21;
char student_name[MAX_NAME_LENGTH];
int student_ident = 1234;
double student_gpa = 4.0;
};

I want to print out this student name using my function "print_student"

void print_student(const student_record record){
std::cout << "Student name: ";
std::cout << record.student_name.c_str();
std::cout << std::endl;

std::cout << "  Student ID: " << record.student_ident << std::endl;
std::cout << "         GPA: " << record.student_gpa << std::endl;
}

I get the error "Intellisense: expression must have class type" The compiler error says "left of .c_str must have class/struct/union." "record" is underlined in red in line 3 of the function and gives the error.

I'm lost here. I tried using very complete scope names and everything but it keeps giving the same error. I'm not sure what's going on and the error seems very... vague.

Upvotes: 0

Views: 39

Answers (2)

Sumeet
Sumeet

Reputation: 779

The problem is with following code. You have initialized the variables in structure:

int student_ident = 1234;
double student_gpa = 4.0;

The correct code should be:

int student_ident;
double student_gpa;

Also while printing the code should be:

std::cout << record.student_name;

Upvotes: 0

The Dark
The Dark

Reputation: 8514

The c_str method is for std::string objects. Your student_name is a character array, so you don't need .c_str() on the end.

However, you are probably better off changing student_name to std::string, then you won't have to worry about all that char copying.

Upvotes: 1

Related Questions