2011-11-24 59 views
0
#include <iostream> 
using namespace std; 

void generCad(int n, char* cad){ 

int longi = 1, lastchar, m = n; // calculating lenght of binary string 
char actual; 
do{ 
    longi++; 
    n /= 2; 
}while(n/2 != 0); 
cad = new char[longi]; 
lastchar = longi - 1; 
do{ 
    actual = m % 2; 
    cad[lastchar] = actual; 
    m /= 2; 
    lastchar--; 
}while(m/2 != 0); 
cout << "Cadena = " << cad; 

}填補新的功能

喜做了一個字符串!我在這裏遇到問題,因爲我需要一個爲數字n創建二進制字符串的函數。我覺得這個過程是「好」,但COUT不打印任何東西,我不知道如何使用新的運營商

回答

1

的代碼應該是這樣的:

void generCad(int n, char** cad) 
{ 
    int m = n, c = 1; 

    while (m >>= 1) // this divides the m by 2, but by shifting which is faster 
     c++; // here you counts the bits 
    *cad = new char[c + 1]; 
    (*cad)[c] = 0; // here you end the string by 0 character 

    while (n) 
    { 
     (*cad)[--c] = n % 2 + '0'; 
     n /= 2; 
    } 
      cout << "Cadena = " << *cad; 
} 

注意,CAD現在字符**和不是char *。如果它只是char *,那麼你不會像指望的那樣得到指針。如果您不需要這個功能外字符串,那麼它可能會爲char *過去,但這時不要忘記刪除CAD你離開的功能(好習慣;-))之前

編輯:

此代碼可能會更容易閱讀,做同樣的:

char * toBin(int n) 
{ 
    int m = n, c = 1; 

    while (m >>= 1) // this divides the m by 2, but by shifting which is faster 
     c++; // here you counts the bits 
    char *cad = new char[c + 1]; 
    cad[c] = 0; // here you end the string by 0 character 

    while (n) 
    { 
     cad[--c] = n % 2 + '0'; 
     n /= 2; 
    } 
    cout << "Cadena = " << cad; 
    return cad; 
} 

int main() 
{ 
    char *buff; 
    buff = toBin(16); 

    delete [] buff; 

    return 1; 

} 
+0

嗨,謝謝,但我不明白你的代碼,我只是想要一個函數,接收一個指向char的指針,並返回指向一個字符串的指針巫婆是二進制字符串n的值。 (修改指針和字符串) – freinn

+0

代碼的輸出是十六進制的! :S,用'generCad(n,&cadena)呼叫;' – freinn

+0

對不起....把*放在cout之前的cad中(已經回答了) – Zoka

0

actual包含數字01,不填補我創建的字符串字符'0''1'。爲了轉換,使用:

cad[lastchar] = actual + '0'; 

而且,由於你使用cad爲C字符串,你需要分配一個多餘的字符添加一個NUL終止。

+0

謝謝,但我已經試過和不工作,我已經改變了這一點:'CAD =新的char [隆基+ 1]; ultimocar = longi - 1; cad [longi] ='\ 0';' – freinn

0
actual = m % 2; 

應該是:

actual = m % 2 + '0';