1

我想制作一个自定义 ITOA 函数将大量数字放入小字符串中,这就是我编写的代码:

main(){
    printf("itoa(2000000000,36)= '%s'",itoa(2000000000,36));
    printf("itoa(36,36)= '%s'",itoa(36,36));
    printf("itoa(37,36)= '%s'",itoa(37,36));

    return 1;
}

stock itoa(val, base)
{
    new buf[1024] = {0,...};
    new i = 1023;
    new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',0};
    for(; val && i; --i, val /= base)
        buf[i] = LETTERZ[val % base];
    return buf[i+1];
}

它基于此页面中的“C”代码:http ://www.jb.man.ac.uk/~slowe/cpp/itoa.html

但不知何故,这是输出:

[20:34:35] itoa(2000000000,36)='X' [20:34:35] itoa(36,36)='1' [20:34:35] itoa(37,36)='1 '

这是完全错误的,我不知道期望哪个输出,但 36 和 37 肯定不能是相同的输出,而且 2 000 000 000 不能只是“X”,因为 X 应该是 35,不是 2 000 000 000,ZZ 应该是 1295 我想...我想以十六进制系统为基础,但使用所有 alfabet 字母。

谁能告诉我这里有什么问题?

我正在使用一种称为 PAWN(也称为 SMALL)的无类型语言,后来我想在 VB.NET 中使用此代码

4

2 回答 2

0
/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char buffer [33];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}

您只给出数字和基数,但参数 2 需要一个指向已分配 char 的指针。使用缓冲区或尝试 NULL,因此该函数将返回结果。

于 2012-09-07T18:48:28.280 回答
0

解决方案似乎很简单,返回 buf[i+1] 只返回一个字符,所以我所做的就是让它返回一个数组:

new _s@T[4096];
#define sprintf(%1) (format(_s@T, SPRINTF_MAX_STRING, %1), _s@T)

main(){
    new num = atoi("ABCDEFG",36);
    printf("%d",num);
    printf("%s",itoa(num,36));

    return 1;
}

stock itoa(val, base)
{
    new buf[1024] = {0,...};
    new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',0};
    for(new pos = 0; val;++pos,val = floatround(val/base,floatround_floor))
        strins(buf,sprintf("%c",LETTERZ[val % base]),0);
    return buf;
}

stock atoi(val[], base)
{
    new CURRNUM = 0;
    new len = strlen(val);
    new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',0};
    for(new i = 0; i < len; ++i)
    {
        for(new x = 0; x < base; ++x)
        {
            new y = (len-i)-1;
            if(val[y] == LETTERZ[x])
            {
                CURRNUM += x*floatround(floatpower(base,i));
            }
        }
    }
    return CURRNUM;
}
于 2012-09-07T22:36:15.577 回答