【发布时间】:2015-04-27 01:58:36
【问题描述】:
所以我试图完全从头开始制作一个程序(不包括库),我有一个非常丑陋的函数:
int parseUnsignedInt ( char * ch, unsigned int * ui )
{
/* Starting at character ch, reads the unsigned int into the
variable ui, returns the number of characters read.
*/
ui = 0; // unsigned integer into which the string representation is read
int m = 1; // multiplier
int ncp = 0; // # of characters parsed
while (*ch)
{
bool chid = false; // ch is a decimal
for (int k = 0; k < decmapLength; ++k)
{
if (decmap[k].cval == *ch)
{
ui += decmap[k].ival * m;
m *= 10;
chid = true;
break;
}
}
if (!chid) break;
++ncp;
++ch;
}
return ncp;
}
它的丑陋部分源于我需要一种方法将characters 与integers ('0'->0, '1'->1, ..., '9'- >9) 并创建一个数组或结构体
typedef struct icpair
{
char cval;
int ival;
} icpair;
icpair decmap [10] = {{'0',0}, {'1',1}, {'2',2}, {'3',3}, {'4',4}, {'5',5}, {'6',6}, {'7',7}, {'8',8}, {'9',9}};
int decmapLength = sizeof(decmap)/sizeof(icpair);
为此目的。但是,如果在纯 C 中有更好的方法来执行此操作,则查找一个值(如果它甚至存在)会导致难看的行数可以被压缩。我也希望这是可靠的,所以没有 ASCII 值减法之类的'9'-'ch'。这在纯 C 中是否可行,如果可以,它是如何实现的?
【问题讨论】:
-
将
ui = 0替换为*ui = 0,将ui += decmap[k].ival * m替换为*ui += decmap[k].ival * m。否则不返回任何内容 -
为什么没有 ASCII 减法?
*ch - '0'正是您要找的。span> -
@JuanLopes 这是否适用于可以编译该程序的所有可能系统?
-
C 规范保证
ch - '0'工作,无论使用哪个字符集,只要ch包含一个从0 到9 的数字。 -
在内部循环中,它可能是:
*ui *= 10;,后跟*ui += decmap[k].ival;,否则“1000”将计算为1。我认为m没有用。
标签: c dictionary data-structures