值字符如何转换为整数?

时间:2018-09-04 13:58:09

标签: c

下面是程序的源代码,如果输入为97,则输出为

Please enter a number between 97 and 121:97

The 1st output is: a
The 2nd output is: a
The 3rd output is b
The 4th output is 97
--------------------------------

此输出背后的逻辑是什么?整数如何转换为字符?是ASCII Chart吗?

#include <stdio.h>
#include <conio.h>
int main () 
{
    int a;
    printf("\n%s enter a number between 97 and 121:" , "Please");
    scanf("%d", &a);
    printf("\nThe 1st outpit is: %c", a);
    printf("\nThe 2nd output is: %c" ,a++);
    printf("\nThe 3rd output is %c", a--);
    printf("\nThe 4th output is %d", a);
    return 0;
}

4 个答案:

答案 0 :(得分:1)

  

此输出背后的逻辑是什么。整数如何转换为字符?

从上下文上讲,您在问如何通过printf 将整数转换为字符The specifications for printf关于%c转换说明符的说法是这样的:

  

如果不存在l长度修饰符,则将int参数转换为   一个未签名的字符,并写入结果字符。

“已转换”一词是指数字转换,由于目标类型是无符号的,因此如果目标类型可以表示该结果,则结果是原始值(如您的示例)。如果无法将其表示为unsigned char,则结果将比可表示的最大unsigned char值模减少1。

但实际上,问题的重点似乎在于该数字如何映射到字符。实际上,C没有指定。这是“执行字符集”的问题,而C对此相当松懈。实际上,执行字符集通常是ASCII的超集,例如UTF-8编码的Unicode或ISO-8859字符集之一,但不是必须的。它甚至可能在运行时根据执行环境而有所不同。

在您的特定运行中,输出与正在使用的ASCII兼容执行字符集一致,并且几乎可以肯定是这种情况,但是您只能通过验证对于由ASCII映射的所有代码点,输出都与ASCII匹配(0-127,包括端点)。

答案 1 :(得分:1)

  

如何将整数转换为字符?

让我们首先看看"%d"

printf("\nThe 4th output is %d", a);

a此时的值为97。当printf()看到"%d"时,它期望看到int作为下一个参数-很好-。 为97导致打印两个字符:'9''7'

  

fprintf c
   int参数以[−] dddd格式转换为带符号的十进制。.
  C11dr§7.21.6.18


现在"%c"

printf("\nThe 1st outpit is: %c", a);

a此时的值为97。当printf()看到"%c"时,它期望看到int作为下一个参数-很好-。然后将int值转换为unsigned char,它仍然是值97。然后“打印”对应于97的字符。尽管ASCII对应的值0-127令人难以置信,所以可以看到字符“ a”。

  

...,将int参数转换为unsigned char,并写入结果字符。

答案 2 :(得分:0)

在下面的示例中,C中的char数据类型中的值可以隐式转换为int数据类型,

char a = 'd'; 
printf("%d", a) 

打印d的十进制ASCII值100。


当我运行上面的代码时,

我刚刚输入了100,即d

$./a.out

Please enter a number between 97 and 121:100

The 1st outpit is: d <= a
The 2nd output is: d <= a++ (post increment, d->e)
The 3rd output is e  <= a-- (decrement e->d)
The 4th output is 100 <= ASCII value of d.

答案 3 :(得分:-2)

根据您的输出,您会发现当您使用%d格式说明符打印整数值时,它的打印结果与您的整数值相同。但是当您使用%c格式说明符打印整数值时,答案将是ASCII字符默认情况下,C编译器以ASCII值形式存储字符数据。这是将整数解释为字符还是整数的方式。有关更多详细信息,请访问https://www.eskimo.com/~scs/cclass/notes/sx6a.html