下面的代码只是询问您的年龄并输出一个简单的 printf。我想做的是输入 000 并让它返回 000 而不仅仅是 0。我该怎么办?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE_LEN 80
#define EXTRA_SPACES 2
int main(void)
{
char line[LINE_LEN + EXTRA_SPACES];
char * end;
int input_num;
/* get user input */
printf("Please enter your age: ");
fgets(line, LINE_LEN+EXTRA_SPACES, stdin);
/* check for buffer overflow */
if(line[strlen(line)-1]!='\n')
{
printf("Error: buffer overflow\n\n");
return EXIT_FAILURE;
}
/* remove newline */
line[strlen(line)-1]=0;
/* retrieve number */
input_num = strtol(line, &end, 0);
if(*end)
{
printf("Error: data entered was not numeric.\n\n");
return EXIT_FAILURE;
}
printf("you are %d years old.\n\n", input_num);
return EXIT_SUCCESS;
}
最佳答案
如果我正确理解你的问题,你需要这样做:
printf("you are %03d years old.\n\n", input_num);
关于c - 当使用strtol并输入2个零(00)时,它只输出一个零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26405172/