错误:无法将'std :: string'转换为'const char *'以将参数'1'转换为'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;}
答案 0 :(得分:9)
您不必使用strncmp
。如果你想要字符串相等,你可以编写如下代码:
if (Courses[i].getGrade() == "A")
// ...
编辑请注意,这适用于std::string
,因为它有一个过载的operator==
答案 1 :(得分:2)
getGrade()返回字符串然后你需要Courses [i] .getGrade()。c_str()
答案 2 :(得分:1)
使用Courses[i].getGrade().c_str()
这将返回字符串缓冲区的char*
(const char*
)。
答案 3 :(得分:1)
我会尝试:
if(strncmp(Courses[i].getGrade().c_str(), "A") == 0)
答案 4 :(得分:0)
我只想将您的getGrage()
函数重写为
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;
};