2013-10-10 75 views
1

我有一個int,我想獲取包含該int的char *。我的代碼是:將int轉換爲char時的奇怪輸出*

int getLength(int x) { 
    int l = 0; 
    while(x) { 
     l++; 
     x /= 10; 
    } 
    return l; 
} 

char* toString(int x) { 
    int l = getLength(x); 
    char *str = new char[l]; 
    l--; // the digits will be placed on positions 0 to l-1 
    while(l >= 0) { 
     str[l] = x % 10 + '0'; 
     x /= 10; 
     l--; 
    } 
    return str; 
} 

一些結果:

toString(1009) = 1009Ä 
toString(23) = 23L 

爲什麼?我只爲l個字符分配空間。 (l = int的長度)

+1

stdlib中有一個函數 - itoa(),它執行此操作。此外,你的字符串緩衝區我們不以null結尾。 – OldProgrammer

+0

@OldProgrammer itoa'雖然不是標準函數。 – Kninnug

+0

這是一個C或C++的問題嗎?在C中,沒有'new',但是在C++中你不會使用'new char []' - 你可以使用簡單的'std :: string'或'std :: vector '。 –

回答

10

您需要null來終止您的字符串。 C字符串是一系列字符,後跟'\0'或空字符;這就是各種字符串處理函數如何知道字符串結束的時間。如果沒有null,C標準字符串處理函數將繼續讀取字符串末尾的任何超出它的值。

記住分配了一個額外的字符,所以你有空間爲空,並存儲'\0'底:

char *str = new char[l+1]; 
str[l] = '\0'; 

順便說一句,new是一個C++運算符。在C中,您將使用malloc()。在C++中,最好使用std::string,因爲它處理分配內存並且不需要空終止。

+1

該代碼將不會適用於負數,順便說一句... – hivert

+0

+1但是,「存儲null,並在末尾存儲'\ 0',這些都是一樣的東西,不是嗎? :) –

+0

@ Moo-Juice對不起,在第一個條款中,我的意思是「分配一個額外的字符來存儲空值」,而在第二個我提到實際存儲它。我說的方式有點不清楚;我會重寫它。 –

4

空字符置於char []的結尾處。你在char []結尾處看到的artifcates是垃圾值。

char* toString(int x) { 
    int l = getLength(x); 
    char *str = new char[l+1]; //+1 for null character 

    str[l]='\0'; // putting null character at the end of char[] 

    l--; 
    while(l >= 0) { 
     str[l] = x % 10 + '0'; 
     x /= 10; 
     l--; 
    } 
    return str; 
} 
0

可以使用日誌10獲得INT的長度,那麼你需要把一個空的字符數組的結束

int getLength(int x) { 
     return ceil(log10(x)); 
    } 
    char* toString(int x) { 
     int l = getLength(x); 
     char *str = new char[l+1]; //+1 for null character 
     str[l]='\0'; // putting null character at the end of char[] 

     while(l >= 0) { 
      str[--l] = x % 10 + '0'; // put the last digit in l - 1 
      x /= 10; 
     } 
} 
+0

如果'x <0','log10(x)'不起作用。 OTOH,OP也不適用於這種'x'。 – chux

1

這不回答你的問題(爲什麼你有趣的輸出,這是由於缺少空終止符作爲其他答案正確指出),但由於你的問題被標記爲C++:在C++中,你甚至不需要自己編寫函數,你可能只是與std::ostringstream

#include <sstream> 
#include <string> 

std::string toString(int x) 
{ 
    std::ostringstream stream; 
    stream << x; 
    return stream.str(); 
}