该程序将字符串转换为 uint64_t
类型并获取错误(如果有)。
在这种情况下,它应该输出 2 个错误(溢出和负数),但没有一个错误出现。此外,它无法正确转换其中一个字符串。
如有任何帮助,我们将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>
#include <limits.h>
int func(const char *buff) {
char *end;
int si;
errno = 0;
const uint64_t sl = strtoull(buff, &end, 10);
if (end == buff) {
fprintf(stderr, "%s: not a decimal number\n", buff);
} else if ('\0' != *end) {
fprintf(stderr, "%s: extra characters at end of input: %s\n", buff, end);
} else if ((sl < 0 || ULONG_MAX == sl) && ERANGE == errno) {
fprintf(stderr, "%s out of range of type uint64_t\n", buff);
} else if (sl > ULONG_MAX) {
fprintf(stderr, "%ld greater than ULONG_MAX\n", sl);
} else if (sl < 0) {
fprintf(stderr, "%ld negative\n", sl);
} else {
si = (int)sl;
}
return si;
}
int main()
{
printf("%d\n", func("123456789123465789"));
printf("%d\n", func("123456789123465789123465789"));
printf("%d\n", func("-1"));
return 0;
}
最佳答案
strtoull();
允许以 '-'
开头的输入。该函数转换文本的数字部分,然后对其求负,结果仍然是一个无符号整数。因此代码无法使用 strtoull()
的结果确定文本是否表示负数,如 uint64_t sl;
, sl < 0
总是错误的。
代码需要检测'-'
以其他方式。
我希望该函数返回 uint64_t
#include <ctype.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
// int func(const char *buff) {
uint64_t func(const char *buff) {
const char *s = buff;
// consume leading whitespace
while (isspace((unsigned char ) *s)) {
s++;
}
int sign = *s;
if (sign == '-' || sign == '+') {
s++;
}
// Now code knows it the text is "negative"
// rest of OP's code needs a some work
char *end;
errno = 0;
unsigned long long sl = strtoull(s, &end, 10);
if (end == s) {
fprintf(stderr, "%s: not a decimal number\n", buff);
} else if ('\0' != *end) {
fprintf(stderr, "%s: extra characters at end of input: %s\n", buff, end);
// } else if ((sl < 0 || ULONG_MAX == sl) && ERANGE == errno) {
} else if (sign == '-') {
fprintf(stderr, "%s negative\n", buff);
sl = 0;
errno = ERANGE;
} else if (ERANGE == errno) {
fprintf(stderr, "%s out of range of type uint64_t\n", buff);
// Only needed on rare machines
#if ULLONG_MAX > UINT64_MAX
else if (sl > UINT64_MAX) {
fprintf(stderr, "%s out of range of type uint64_t\n", buff);
sl = UINT64_MAX;
errno = ERANGE;
}
#endif
}
return (uint64_t) sl;
}
OP 返回 int
很奇怪。留下更新main()
到OP。
关于C - 字符串到 uint64_t 的转换,并进行错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46325780/