将字符串与C ++中的字符进行比较

时间:2010-11-20 20:05:18

标签: c++

嘿,伙计们,我正在努力编写一个计算学生GPA的程序。出于某种原因,编译器在比较两个字符串时给出了一个错误,但我似乎无法找到它的原因。下面你会发现给我错误的代码片段。如果有人能帮助我搞清楚,我真的很感激。

错误:无法将'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;}

5 个答案:

答案 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;
 }; 
相关问题