C++字符转ASCII值代码编译错误:invalid cast问题排查
Hey there! Let's break down why your code is hitting that compilation error and fix it right up.
错误原因分析
Your code uses a std::string variable to hold a single character, then tries to cast the entire string directly to an int — this is an invalid type conversion in C++. The compiler has no built-in way to translate a full string object into an integer value, which is exactly what that error message is flagging.
修正方案(最优解)
Since you're only trying to get the ASCII value of a single character, you don't need a std::string at all. Switch to a char type instead: it's designed specifically for single characters, and can be safely cast to an int to retrieve its corresponding ASCII value.
#include <iostream> using namespace std; int main() { char c; cout << "Enter a character: "; cin >> c; cout << "ASCII Value of " << c << " is " << int(c); return 0; }
备选方案(如果必须用std::string)
If for some reason you need to keep using a std::string (like handling potential multi-character input but only caring about the first character), you can access the string's first character with c[0] and cast that to int. We also added a check for empty input to avoid undefined behavior:
#include <iostream> #include <string> using namespace std; int main() { string c; cout << "Enter a character: "; cin >> c; if (!c.empty()) { cout << "ASCII Value of " << c[0] << " is " << int(c[0]); } else { cout << "You didn't enter a character!"; } return 0; }
内容的提问来源于stack exchange,提问作者jamie's

