【问题标题】:assign numeric value of digit into char using scanf使用 scanf 将 digit 的数值赋给 char
【发布时间】:2020-07-15 09:54:25
【问题描述】:

如果我有一个字符:char ch

我想给它分配一个数字的数值,例如,如果用户输入 0,我希望 char 的值为 0 ('\0') 而不是 48 ('0')

如果我尝试scanf("c", &ch),它将分配48(ascii 值为0),如果我尝试scanf("d", &ch),则会出现错误。

我知道可以通过将其接收为字符串,然后将其转换为char,然后使用ch-'0'来获取数值来完成,但是没有这些额外的步骤是否可以?

【问题讨论】:

  • 将输入读入int,然后将int分配给char
  • @user3121023 我在使用 printf 时是否也需要使用 %hhd ?还是 %d 好吗?
  • @user3121023 我用的是C90,不支持hhd
  • @avivgood2:停止使用 C 1990。
  • avivgood2,你用的是什么编译器?

标签: c char scanf return-value c89


【解决方案1】:

使用scanf将数字的数值赋给char

从C99开始,直接的方式是

char ch;
scanf("%hdd", &ch);
// or to insure reading only 1 character
scanf("%1hdd", &ch);

在此之前,以下是常见的。 @Lundin

char ch;
int ch_int;
if (scanf("%d", &ch_int) == 1) {
  ch = ch_int;

或读取char 并将其字符值转换为数值。 (OP对此已经很熟悉了)

char ch;
scanf("%c", &ch);
ch -= '0';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2018-04-03
    • 2021-04-07
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多