我的程序中有一个辅助函数
long parse_int (char * cp, int * i)
{
/*
Helper function
cp: Pointer to a character array that is a base-10 string representation of an integer
i: Pointer to an integer which will store the output of the parsing of cp
Returns the number of characters parsed.
*/
long n = 0;
*i = 0;
while (cp!= '\0')
{
char c = *cp;
long k = index_of(digits, c);
if (k > -1)
{
n = n * 10 + k;
}
else
{
break;
}
++cp;
}
return n;
}
里面使用的东西在哪里
long index_of (char * pc, char c)
{
/*
Helper function
pc: Pointer to the first character of a character array
c: Character to search
Returns the index of the first instance of
character c in the character array str. If
none is found, returns -1.
*/
char * pfoc = strchr(pc, c); /* Pointer to the first occurrence of character c */
return pfoc ? (pfoc - pc) : -1;
}
和
char digits [] = "0123456789";
如果可能的话,我想通过最大限度地利用标准库的火力来减少代码量。我完全了解atoi,但问题是我无法调用它并恢复它在调用时解析的字符数。有什么建议吗?
最佳答案
您可以使用strtol()
,但你必须做一些工作才能相当安全:
#include <errno.h>
#include <stdlib.h>
#include <limits.h>
int strtoi(const char *data, char **endptr, int base)
{
int old_errno = errno;
errno = 0;
long lval = strtol(data, endptr, base);
if (lval > INT_MAX)
{
errno = ERANGE;
lval = INT_MAX;
}
else if (lval < INT_MIN)
{
errno = ERANGE;
lval = INT_MIN;
}
if (errno == 0)
errno = old_errno;
return (int)lval;
}
这是我的 strtoi()
函数,它使用标准 strtol()
来完成这项艰苦的工作。请注意不要(永久)将 errno 设置为 0,因为没有标准库函数会这样做。你可以这样使用它:
char *end;
int intval = strtoi(str, &end, 0);
或者你可以草率地使用:
char *end;
int intval = strtol(str, &end, 0);
当“主题”字符串大于 int
的容纳范围,但不大于 long
的容纳范围时,就会出现差异; strtoi()
函数将返回值限制为 INT_MAX
或 INT_MIN
,但草率的技术通常只给出低位 4 个字节long
中存储的任何值,如果您有 64 位 long
和 32 位 int
值,则可能会产生误导。
请注意,调用代码应检查 intval == INT_MAX
或 intval == INT_MIN
和 errno != 0
以检测溢出。
您可以按照以下方式编写您的 parse_int()
函数:
long parse_int (char *cp, int *i)
{
char *end;
*i = strtoi(cp, &end, 10); // You want decimal
return(end - cp);
}
关于c - 有没有办法使用 C 标准库来转换 string----->int 并跟踪解析的字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28667132/