我用下面方法:
#include <iostream>
char *str = "com";
char *cnum = 0; 
int i = 12;sprint(cnum, "%d", i);
strcpy(str, cnum);但不知道能不能得到“com12”数据。请问各位用什么方法?

解决方案 »

  1.   

    你的程序有问题:
    char * str = "com"; //这样不行吧?
      

  2.   

    char str[11]={"com"};
    char cnum[11];
    sprint(cnum, "%d", i);
    strcpy(str, cnum);之所以定义11的空间,是由于int最长时10个字节,多一个为结束符
    你的错误在于没有为cnum分配空间,然后向0处写值,那是不可访问的
    即使那里成功了,strcpy(str, cnum);也可能出错,当cnum大于3个字符时(包结束符4个字节),就错了,因为str只有4个空间,你将覆盖后面的东东,后果不堪设想!
      

  3.   

    我不清楚你用什么开发如果用ATL请不要用sprintf
    要用wsprintf,原因,我记不清楚了.你的用下面方法:
    #include <iostream>
    char *str = "com";
    char *cnum = 0; 
    int i = 12;sprint(cnum, "%d", i);
    strcpy(str, cnum);我的方法:
    #include <iostream>
    const char * cpchStr = "com";
    char *pchBuf = NULL; //存储缓存.
    char *pchNum = NULL; //请不要用0,不好.
    int iNum = 12; //请不要使用i,i一般是用来做计数器的.int iCharTypeSize = sizeof(char); //获得char的长度.
    int iIntTypeStrLen = 5 + 1; //请在系统初始化的时候,测试int类型的数值范围,
                         //来确定其转为字符串的长度.加一是为了存储'\0';//求取字符串长度,我忘记了.我就用lstrlen来代替吧.
    //申请空间,呵呵,我喜欢用malloc,喜欢自己处理.呵呵.
    int iBufLen = lstrlen(cpchStr) + iIntTypeStrLen + 1; //
    if (iBufLen < 0)
    {
      //长度溢出进行处理.
      return ERROR; //返回错误.错误号,自己编.
    }
    pchNum = (char *)malloc( iCharTypeSize  * iIntTypeStrLen );
    if (pchNum == NULL)
    {
      //空间申请失败,处理错误.
      return ERROR;
    }
    //清理申请的空间.
    memset( pchNum, 0, iIntTypeStrLen );char * pchBuf = (char *) malloc(iCharTypeSize * iBufLen);
    if (pchBuf == NULL)
    {
       //申请空间失败.
       free( pchNum ); //释放申请的空间pchNum
       return ERROR;
    }memset( pchBuf, 0, iBufLen ); //清理空间.
    wsprintf( pchNum, "%d", iNum); 
    strcpy(pchBuf, pchNum);
    如有不足的地方,请大虾们多多指教.我的信箱[email protected]
      

  4.   

    int iBufLen = lstrlen(cpchStr) + iIntTypeStrLen + 1; //这一句,应该改为
    int iBufLen = lstrlen(cpchStr) + iIntTypeStrLen; //
    我多用了一个字节,呵呵.
      

  5.   

    哦,对了char *pchBuf,我声明了两次,请把后边那个char * 删掉,只留个pchBuf,呵呵,我写错了.最近使用c#,把我好多风格都给改了.