【问题标题】:Reading an integer, one digit at a time读取一个整数,一次一位数
【发布时间】:2017-04-03 13:01:43
【问题描述】:

我已经看到以下代码工作:

int d1, d2, d3, d4, d5;
printf("Enter group of five digits: ");
scanf("%1d%1d%1d%1d%1d", &d1, &d2, &d3, &d4, &d5);

但是下面的代码失败了:

int ar[5], counter = 0;
printf("Enter number: ");
while(counter < 5){
    scanf("%1d", &ar[counter]);
    counter++;
}

失败代码中的数字都是32767。这是为什么呢?

编辑:我刚刚在这里给出了一个代码片段。我正在尝试 K.N.King 的 C Programming: A Modern Approach 中的练习题

我看到第二个代码片段因一一打印出数组内容而失败。

在这里看到很多负面回应,没有任何解释我应该如何构建我的问题,这根本没有帮助。另外,我确信有其他方法可以解决这个问题,但我只是问为什么第二个代码片段在第一种情况下失败。

编辑 2:作为输入,我输入一个 5 位数字,然后输入键:比如 12345\n。在第一个片段中,1 存储在 d1 中,2 存储在 d2 中,依此类推。

在第二个代码片段中,ar[0] 是 32767 而不是 1,依此类推。所以它失败了。

【问题讨论】:

  • 使用 getch() 然后转换它
  • 输入是什么?循环后ar 的内容是什么?你检查过scanf 返回的内容吗?
  • "失败代码中的数字都是 32767" --> 代码不会打印出数字。他们的价值观是如何确定的?
  • 如何打印数组,输入是什么?
  • 你的代码的两种变体对我来说都很好,通过成功写回输入的数字来验证。

标签: c arrays conversion-specifier


【解决方案1】:

试试这个:

#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[]) {
    printf("Enter group of five digits: ");
    char number[5];
    scanf("%s", &number);

    int digits[5];
    for (int i = 0; i < 5; i++) {
        digits[i] = number[i] - '0';
    }

    printf("d1=%d d2=%d d3=%d d4=%d d5=%d", digits[0], digits[1], digits[2],
           digits[3], digits[4]);
    getch();
}

【讨论】:

    猜你喜欢
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2011-08-10
    相关资源
    最近更新 更多