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

C++字符转ASCII值代码编译报错:char转const char*无效转换

Fixing the Compilation Error in Your C++ ASCII Value Program

Hey there! Let's sort out that error you're hitting with your code.

What's Causing the Error?

The problem lies in line 9 of your code: string(c). Here's the breakdown:

  • The std::string class doesn't have a constructor that accepts a single char directly. When you try to pass c (a char) to string(), the compiler tries to convert it to a const char* (a pointer to a C-style string), which isn't valid—you can't treat a single character as a pointer. That's exactly what the error invalid conversion from 'char' to 'const char*' is warning you about.
  • On top of that, this line doesn't even achieve your goal: you want to print the numeric ASCII value of the character, not create a string from it.

The Fixed Code

To get the ASCII value, you just need to convert the char to an int (since char is essentially a small integer type storing the ASCII code under the hood). Here's the corrected version:

#include <iostream>
using namespace std;

int main() {
    char c;
    cout << "Enter a character: ";
    cin >> c;
    // Cast the char to int to reveal its ASCII value
    cout << "ASCII Value of " << c << " is " << static_cast<int>(c);
    return 0;
}

Key Explanations

  • static_cast<int>(c) is a safe, C++-style way to convert the char to its integer equivalent. You could also use a C-style cast like (int)c, but static_cast is better because it's explicit and avoids unintended conversions.
  • When you output c directly (e.g., cout << c), it prints the character itself. Casting it to int tells cout to print the numeric ASCII value instead.

For example, if you input 'B', the program will output:

ASCII Value of B is 66

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:44:57