C - 字符串到 uint64_t 的转换,并进行错误处理

标签 c error-handling string-parsing

该程序将字符串转换为 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/

相关文章:

c++ - 在 C 或 C++ (mac OSX) 中拥有 KeyDown 事件

python - 程序问题

java - 在 Java 中解析字符串以用特定数据替换标记

python - 解析文本文件中的文本 block (由空行分隔的 block )

c - 使用结构在C中解析数据包

c - 读取 P6 二进制 ppm 文件

c - 是什么导致堆栈溢出?

authentication - 在中心位置或组件中捕获错误

java - 如何正确重构 Java 方法以进行正确的错误处理

c# - 正则表达式匹配但忽略输出中的特定字符