2016-04-10 48 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',而不是數組,因此只有第一個數字被保留。 –