简体   繁体   English

在 C 中打印字符及其 ASCII 码

[英]Printing chars and their ASCII-code in C

如何在 C 中打印字符及其等效的 ASCII 值?

This prints out all ASCII values:这将打印出所有 ASCII 值:

int main()
{
    int i;
    i=0;
    do
    {
        printf("%d %c \n",i,i);
        i++;
    }
    while(i<=255);
    return 0;
}

and this prints out the ASCII value for a given character:这将打印出给定字符的 ASCII 值:

int main()
{
    int e;
    char ch;
    clrscr();
    printf("\n Enter a character : ");
    scanf("%c",&ch);
    e=ch;
    printf("\n The ASCII value of the character is : %d",e);
    getch();
    return 0;
}

Try this:试试这个:

char c = 'a'; // or whatever your character is
printf("%c %d", c, c);

The %c is the format string for a single character, and %d for a digit/integer. %c 是单个字符的格式字符串,%d 是数字/整数。 By casting the char to an integer, you'll get the ascii value.通过将 char 转换为整数,您将获得 ascii 值。

To print all the ascii values from 0 to 255 using while loop.使用 while 循环打印从 0 到 255 的所有 ascii 值。

#include<stdio.h>

int main(void)
{
    int a;
    a = 0;
    while (a <= 255)
    {
        printf("%d = %c\n", a, a);
        a++;
    }
    return 0;
}

Nothing can be more simple than this没有比这更简单的了

#include <stdio.h>  

int main()  
{  
    int i;  

    for( i=0 ; i<=255 ; i++ ) /*ASCII values ranges from 0-255*/  
    {  
        printf("ASCII value of character %c = %d\n", i, i);  
    }  

    return 0;  
}   

Source: program to print ASCII value of all characters来源: 打印所有字符的 ASCII 值的程序

#include<stdio.h>
 void main()
{
char a;
scanf("%c",&a);
printf("%d",a);
}

This reads a line of text from standard input and prints out the characters in the line and their ASCII codes:这从标准输入中读取一行文本并打印出该行中的字符及其 ASCII 代码:

#include <stdio.h>

void printChars(void)
{
    unsigned char   line[80+1];
    int             i;

    // Read a text line
    if (fgets(line, 80, stdin) == NULL)
        return;

    // Print the line chars
    for (i = 0;  line[i] != '\n';  i++)
    {
        int     ch;

        ch = line[i];
        printf("'%c' %3d 0x%02X\n", ch, ch, (unsigned)ch);
    }
}

Chars within single quote ('XXXXXX'), when printed as decimal should output its ASCII value.单引号 ('XXXXXX') 内的字符,当打印为十进制时,应输出其 ASCII 值。

int main(){

    printf("D\n");
    printf("The ASCII of D is %d\n",'D');

    return 0;

}

Output:输出:

% ./a.out
>> D
>> The ASCII of D is 68

Simplest approach in printing ASCII values of a given alphabet.打印给定字母表的 ASCII 值的最简单方法。

Here is an example :这是一个例子:

#include<stdio.h>
int main()
{
    //we are printing the ASCII value of 'a'
    char a ='a'
    printf("%d",a)
    return 0;
}

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

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