You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++报错:const char*转char无效转换 [-fpermissive] 求助

错误原因与修正方案

你的代码触发错误的核心原因是混淆了C++中字符与字符串的表示方式:

  • char类型变量存储单个字符,必须用单引号(')包裹赋值,比如'O'、'A';
  • 双引号(")包裹的是字符串字面量,它的实际类型是const char*(指向字符数组的指针),无法直接赋值给char类型变量,这就是错误提示的来源。

错误代码行

所有给grade赋值的语句都存在这个问题:

grade = "O";  // 错误:"O"是const char*,不能赋值给char
grade = "A";  // 同样错误
// ... 其他类似行

修正后的完整代码

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main(){
    int score{};
    cout << "Enter the score you got(0 - 100): ";
    cin >> score;
    
    char grade{};
    if(score>=0 && score<=100){
      if(score >= 90)
          grade = 'O';  // 改为单引号
      else if(score >= 80)
          grade = 'A';  // 改为单引号
      else if(score >= 70)
          grade = 'B';  // 改为单引号
      else if(score >= 60)
          grade = 'C';  // 改为单引号
      else if(score >= 50)
          grade = 'D';  // 改为单引号
      else
          grade = 'F';  // 改为单引号
      cout << "Your grade is: " << grade << endl;
      
      if(grade == 'F')
          cout << "Sorry, you should give it a try again" << endl;
      else
          cout << "Well done!" << endl;
    }else{
        cout << "Sorry, the score you entered is not in range." << endl;
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Thasneem Mohamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 05:40:12