C/C++ 中的 asc 和 chr 等效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6405137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:04:45  来源:igfitidea点击:

asc and chr equivalent in C/C++

c++cchr

提问by Appster

Well the title pretty much sums it up. I want to use something like asc("0") in C++, and want to make the program platform independent so don't want to use 48! Any help appreciated.

好吧,标题几乎总结了它。我想在 C++ 中使用 asc("0") 之类的东西,并且想让程序平台独立,所以不想使用 48!任何帮助表示赞赏。

回答by nibot

You can simply use single-quotes to make a character constant:

您可以简单地使用单引号使字符常量:

char c = 'a';

The character type isa numeric type, so there is no real need for ascand chrequivalents.

字符类型数字类型,因此没有真正的需要ascchr等价物。

Here's a small example that prints out the character values of a string:

这是一个打印出字符串字符值的小示例:

#include <stdio.h>

int main(int argc, char **argv) {
  char str[] ="Hello, World!";

  printf("string = \"%s\"\n", str);

  printf("chars = ");
  for (int i=0; str[i] != 0; i++) 
    printf("%d ", str[i]);
  printf("\n");

  return 0;
}

The output is:

输出是:

string = "Hello, World!"
chars = 72 101 108 108 111 44 32 87 111 114 108 100 33 

回答by Vinicius Kamakura

In C and C++, if you use a character enclosed by ''and not ""it means you are dealing with its raw binary value already.

在 C 和 C++ 中,如果您使用由''和 not括起来的字符,""则表示您已经在处理其原始二进制值。

Now, in C and C++, "0"is a literal two byte null-terminated string: '0'and '\0'. (ascii 48 ascii 0)

现在,在 C 和 C++ 中,"0"是一个字面量的两字节空终止字符串:'0'and '\0'。(ASCII 48 ASCII 0)

You can achieve what you want by using var[0]on a "" null-terminated string or use one of the conversion routines. (atoi()in C, stringstreamlib in C++)

您可以通过var[0]在 "" 以空字符结尾的字符串上使用或使用转换例程之一来实现您想要的。(atoi()在 C 中,stringstream在 C++ 中为 lib)

回答by iolo

You will get the ASCII value of a 0 character by writing: '0'.
Likewise 'char' for every char you need.

您将通过编写以下内容获得 0 字符的 ASCII 值:'0'。
对于您需要的每个字符,同样使用“字符”。