简体   繁体   English

初始化期间如何在C中将char转换为int

[英]How to convert a char to int in C during initialization

I want to compare two char types in C++. 我想比较C ++中的两种char类型。 I tried cout<<"x"=="x"; 我尝试了cout<<"x"=="x"; to see the result and it wont work(which I believe is normal), so I tried converting it by trying int letter = "x" to try to compare it by it ASCII number. 看到结果,它将无法正常工作(我相信这是正常的),因此我尝试通过尝试int letter = "x"来进行转换,以尝试通过ASCII数字对其进行比较。 This gets me the error; 这给了我错误。

error:invalid conversion from 'const char*' to 'char' 错误:从'const char *'到'char'的无效转换

Shouldn't this work? 这不行吗? If not, what should I be doing? 如果没有,我该怎么办?

"x" gives you a nul-terminated array of characters {'x','\\0'} . "x"为您提供了一个以nul终止的字符数组{'x','\\0'}

Use 'x' if you want a single char 如果您需要一个char请使用'x'

  • "x" is an array of chars - string - (2 bytes - one for char x , one for char \\0 nul) "x"是一个字符数组-字符串-(2个字节-一个用于char x ,一个用于char \\0 nul)
  • 'x' is char - variable represented by 1 byte in memory. 'x'是char-由内存中的1个字节表示的变量。

Assigning "x" to an int variable is an obvious mistake. "x"分配给int变量是一个明显的错误。

Try 'x' instead of "x" : int letter = 'x'; 尝试用'x'代替"x"int letter = 'x'; should work fine. 应该工作正常。

You are using double quotes around your characters. 您在字符周围使用双引号。

Double quotes are of type const char*, not type char 双引号是const char *类型,而不是char类型

Try 尝试

int letter = 'x';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM