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::stringclass doesn't have a constructor that accepts a singlechardirectly. When you try to passc(achar) tostring(), the compiler tries to convert it to aconst 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 errorinvalid 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 thecharto its integer equivalent. You could also use a C-style cast like(int)c, butstatic_castis better because it's explicit and avoids unintended conversions.- When you output
cdirectly (e.g.,cout << c), it prints the character itself. Casting it tointtellscoutto 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
相关产品推荐
相关产品推荐

