2016-04-10 50 views
-2

我需要保留输入中的任何前导零,因此我将数字作为char s,然后使用ctoi()函数将它们转换回整数,作为在此代码中显示:输入数字(可能带有前导零)但输出时不带前导零

#include<stdio.h> 

#define ctoi(a) a-'0' 

int main() { 
    int n; 
    char ch; 
    scanf("%c",&n); 
    ch=ctoi(n); 
    printf("%d",n); 
} 

但该代码无效。问题是什么?

Input: 

001 

78 
00

Expected Output: 

1 
123 
78 
123 

But I got: 

1 
1 
7 
1 
+0

您需要['scanf'(和相关函数)引用](http://en.cppreference.com/w/c/io/fscanf)。用所有格式代码检查表格。 –

回答

0

当您将数字存储为整数时,您只存储实际数字,而不是用于制作该数字的格式。如果您想要保留格式,您需要将其存储为字符串或其他一些存储原始格式的方法。

int n = 10; // only stores a number in memory 
char text[10] = "00010"; // stores any text, but can not be used for number arithmetic as stored here 
+0

更糟糕的是,OP使用_single_'char',而不是数组,因此只有第一个数字被保留。 –