在C中以数字打印前导零

时间:2018-08-18 21:32:17

标签: c numbers digit leading-zero

我正在一个项目上,我希望我的程序读取前导零的严格5位数字。

如何打印包含前导零的数字?
:如何提供程序读取5位数字(包括0作为前导数字)的信息?

3 个答案:

答案 0 :(得分:1)

我假设您想读int变量。如果是这样,您可以尝试以下解决方案。

#include<stdio.h>
void main()
{
  int a;

  scanf("%5d", &a);
  printf("%05d",a);

}

答案 1 :(得分:1)

使用带有'%05d'的printf系列打印带有前导零的数字。使用sscanf读取该值(忽略前导零)。

咨询以下代码:

int a = 25;
int b;
char buffer[6];
sprintf( buffer, "%05d", a );
printf( "buffer is <%s>\n", buffer );
sscanf( buffer, "%d", &b );
printf( "b is %d\n", b );

输出为:

缓冲区是<00025>

b是25

答案 2 :(得分:1)

最好控制输入的方法是读取一个字符串,然后根据需要解析/分析该字符串。例如,如果“正好五个数字”表示:“正好5个数字(不少于,不多),除了'0'以外没有其他前导字符,并且没有负数”,那么可以使用函数strtol ,它告诉您数字解析在哪里结束。从中,您可以得出输入实际上有多少位数:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int main() {

    char line[50];
    if (fgets(line,50,stdin)) {
        if (isdigit((unsigned char)line[0])) {
            char* endptr = line;
            long number = strtol(line, &endptr, 10);
            int nrOfDigitsRead = (int)(endptr - line);
            if (nrOfDigitsRead != 5) {
                printf ("invalid number of digits, i.e. %d digits (but should be 5).\n", nrOfDigitsRead);
            } else {
                printf("number: %05lu\n", number);
            }
        }
        else {
            printf ("input does not start with a digit.\n");
        }
    }
}