Reputation: 21
Hey Guys, I'm trying to write a program that calculates the GPA of a student. For some reason the compiler is giving me an error when comparing two strings, but I cant seem to find the reasons for it. Below you will find the piece of code that is giving me error. I would really appreciate if someone could help me figure it out.
ERROR: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int strncmp(const char*, const char*, size_t)’
double StudentInfo::getGPA() {
double temp = 0;
for(int i = 0; i < totalCourses; i++) {
if(strncmp(Courses[i].getGrade(), "A") == 0) //Gets string "grade", and compares it to "A".
temp = temp + 4;
if(strncmp(Courses[i].getGrade(),"A-", 2) == 0)
temp = temp + 3.7;
if(strncmp(Courses[i].getGrade(), "B+", 2) == 0)
temp = temp + 3.3;
if(strncmp(Courses[i].getGrade(), "B") == 0)
temp = temp + 3;
if(strncmp(Courses[i].getGrade(), "B-", 2) == 0)
temp = temp + 2.7;
if(strncmp(Courses[i].getGrade(), "C+", 2) == 0)
temp = temp + 2.3;
if(strncmp(Courses[i].getGrade(), "C") == 0)
temp = temp + 2;
if(strncmp(Courses[i].getGrade(), "C-") == 0)
temp = temp + 1.7;
if(strncmp(Courses[i].getGrade(), "D+") == 0)
temp = temp + 1.3;
if(strncmp(Courses[i].getGrade(), "D") == 0)
temp = temp + 1;
else
temp = temp + 0;
}
GPA = temp/totalCourses;
return GPA;}
Upvotes: 2
Views: 346
Reputation: 14870
I would just rewrite your getGrage()
function to be
float getGrade(){
float grade = 1 + 'D' - toupper(grade[0]);
if (grade < 1 || grade > 4)
return 0;
if (grade[1] == '+') return grade + 0.3;
if (grade[1] == '-') return grade - 0.3;
return grade;
};
Upvotes: 0
Reputation: 79893
You do not have to use strncmp
for this. If you want string equality you can write code like this:
if (Courses[i].getGrade() == "A")
// ...
edit Note that this works for std::string
because it has an overloaded operator==
Upvotes: 9
Reputation: 6857
I would try:
if(strncmp(Courses[i].getGrade().c_str(), "A") == 0)
Upvotes: 1
Reputation: 11088
use Courses[i].getGrade().c_str()
this returns char*
(const char*
) of string buffer.
Upvotes: 1
Reputation: 3505
getGrade() return string then you need Courses[i].getGrade().c_str()
Upvotes: 2