【问题标题】:Storing Integers in an Char Array in C在 C 中将整数存储在 Char 数组中
【发布时间】:2019-06-12 19:33:03
【问题描述】:

我正在为 Uni 做一些工作并编写了一个程序,它将整数存储在一个 char 数组中,并将它们转换为它们的 ASCII 值并在最后打印它们。我的代码之前没有工作,只有当我在我的 scanf 行中将“%c”更改为“%i”时才开始工作。我的问题:当我想将这些数字存储在 char 数组而不是 Int 数组中时,为什么它必须是“%i”。谢谢!

我的代码:

#include <stdio.h>

int main()
{

    int i; /counter
    char numbers[12];
    printf("Please enter 12 Numbers\n");
    for(i = 0; i < 12; i++){
        printf("please enter the  %i. Number\n", i+1);
        scanf("%i", &numbers[i]);// <-- changed "%c" to "%i" and it worked.why?

    }
    for(i = 0; i < 12;i++){
        printf("The %i.ASCII value is %i and has the Char %c\n", i+1, numbers[i], numbers[i]);
    }




    return 0;
}

【问题讨论】:

  • 这是未定义的行为。 %i 用于 int,但您尝试阅读 char。你试过%hhi吗?
  • 请发布使用的输入示例和所需的输出。
  • 他们可能希望您通过 %d 或 %i 将数字读取为 int,然后将 int 转换为 char。不要用 %hhi 直接将其存储在 char 中,因为然后 scanf 会处理转换。

标签: c arrays


【解决方案1】:

%c 用于读取单个字符。例如,如果您输入"123"scanf 会将'1' 读入char 变量并将其余部分留在缓冲区中。

另一方面,%iint 的说明符,因此在尝试读取 char 时会导致未定义的行为。

我认为您正在寻找的是 %hhi 说明符,它将一个数字读入 char 变量。

【讨论】:

  • 非常感谢您的回答!在我的讲座中从未听说过 %hhi,所以基本上教授可能想要 %i 方法,但 %hhi 工作得很好!
  • @informatiker 通常,老师希望您阅读您正在使用的功能的规范。 ;)
猜你喜欢
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 2010-12-28
  • 2016-04-28
  • 2013-11-03
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多