2011-11-24 22 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';