c - 读取一串以逗号分隔的数字

标签 c string algorithm csv error-handling

我正在编写一个函数,该函数应该读取一串数字,以逗号分隔。字符串的格式如下:

"1, 2, 3"

唯一的“规则”是该函数将容忍任何空格或制表符,只要每个数字之间有一个逗号即可。

如果字符串有效,则数字将存储在链接列表中。

例如,以下字符串有效:

"1,2,14,2,80"
"  250  ,  1,  88"

但以下内容无效:

" 5, 1, 3 ,"
"51, 60, 5,,9"

我首先尝试了strtok()(使用分隔符“,\t”,但根据我目前的理解,不可能检查错误。所以我编写了自己的函数,但我非常不高兴有了它 - 我认为代码非常糟糕,虽然它似乎可以工作,但我真的很想知道是否有更干净、更简单的方法来实现这样的功能。

我的职能是:

void sliceNumbers(char * string)
{
  /*flag which marks if we're expecting a comma or not*/
  int comma = FALSE;
  /*Are we inside a number?*/
  int nFlag = TRUE;
  /*error flag*/
  int error = FALSE;
  /*pointer to string start*/
  char * pStart = string;
  /*pointer to string end*/
  char * pEnd = pStart;

  /*if received string is null*/
  if (!string)
  {
    /*add error and exit function*/
    printf("You must specify numbers");
    return;
  }
  /*this loop checks if all characters in the string are legal*/
  while (*pStart != '\0')
  {
    if ((isdigit(*pStart)) || (*pStart == ',') || (*pStart == ' ') || (*pStart == '\t'))
    {
      pStart++;
    }
    else
    {
      char tmp[2];
      tmp[0] = *pStart;
      tmp[1] = 0;
      printf("Invalid character");
      error = TRUE;
      pStart++;
    }
  }
  if (!error)
  {
    pStart = string;
    if (*pStart == ',')
    {
    printf("Cannot start data list with a comma");
    return;
    }
    pEnd = pStart;
    while (*pEnd != '\0')
    {
      if (comma)
      {
        if (*pEnd == ',')
        {
          if (!nFlag)
          {

          }
          if (*(pEnd + 1) == '\0')
          {
            printf("Too many commas");
            return;
          }
          *pEnd = '\0';
          /*Add the number to the linked list*/
          addNumber(pStart, line, DC);
          comma = FALSE;
          nFlag = FALSE;
          pStart = pEnd;
          pStart++;
          pEnd = pStart;
        }
        else if (isdigit(*pEnd))
        {
          if (!nFlag)
          {
            printf("numbers must be seperated by commas");
            pEnd++;
          }
          else
          {
            if (*(pEnd + 1) == '\0')
            {
              pEnd++;
              /*Add the number to the linked list*/
              addNumber(pStart);
              comma = FALSE;
              nFlag = FALSE;
              pStart = pEnd;
              pStart++;
              pEnd = pStart;
            }
            else
            {
              pEnd++;
            }
          }
        }
        else if (*pEnd == '\0')
        {
          if (nFlag)
          {
            /*Add the number to the linked list*/
            addNumber(pStart, line, DC);
          }
          else
          {
            printf("Too many commas");
          }

        }
        else if (*pEnd == ' ' || *pEnd == '\t')
        {
          nFlag = FALSE;
          pEnd++;
        }
      }
      else
      {
        if (*pEnd == ',')
        {
          printf("There must be only 1 comma between numbers");
          return;

        }
        else if (isdigit(*pEnd))
        {
          if (*(pEnd + 1) == '\0')
          {
            pEnd++;
            /*Add the number to the linked list*/
            addnumber(pStart, line, DC);
            comma = FALSE;
            nFlag = FALSE;
            pStart = pEnd;
            pStart++;
            pEnd = pStart;
          }
          else
          {
            pStart = pEnd;
            pEnd++;
            nFlag = TRUE;
            comma = TRUE;
          }
        }
        else if (*pEnd == ' ' || *pEnd == '\t')
        {
          if (!nFlag)
          {
            pEnd++;
          }
          else
          {
            pEnd++;
          }
        }
      }
    }
  }
}

最佳答案

您已经定义了许多 bool 值(尽管您已将它们声明为 int)来跟踪当前状态。您可以将这些组合成一个 state 变量,使用 #define 定义可能的值:

#define STATE_START 0
#define STATE_IN_NUMBER 1
#define STATE_COMMA 2
#define STATE_FINISHED 3
#define STATE_ERROR 4

int state = STATE_START;

您可以绘制一个图表(有点像流程图)来显示每个角色如何将我们从一种状态转移到另一种状态。

enter image description here

(对于我的图像,我保持简单,仅显示不带空格的输入的非错误状态)

或者直接用文字表达:

current state   | input     | next state| side effect
-----------------------------------------------------------------------
START           | digit     | IN_NUMBER | start storing a number
START           | other     | ERROR     | 
IN_NUMBER       | digit     | IN_NUMBER | continue storing a number
IN_NUMBER       | comma     | COMMA     | complete storing a number
IN_NUMBER       | null      | FINISHED  | finalise output
IN_NUMBER       | other     | ERROR     | report error
COMMA           | digit     | IN_NUMBER | start storing a number
COMMA           | comma     | ERROR     |
COMMA           | other     | ERROR     |

(对于我的表,我添加了基本错误状态,但仍然没有考虑空格)

您将需要添加更多状态和转换来处理空格和制表符,但原则不会改变。我建议从一个无需空格的实现开始,然后添加到其中。

这允许您编写一个有限状态机,其实现如下所示:

int state = STATE_START;
while(state != STATE_FINISHED && state != STATE_ERROR) {
    char c = input[offset++];
    switch(state) {
        case STATE_START:
            state = handleStateStart(...);
            break;
        case STATE_IN_NUMBER:
            state = handleInNumber(...);
            break;
        // etc.
        default:
            sprintf(error_message, "Reached unsupported state: %c", state);
            state = STATE_ERROR;
    }
}

处理函数的参数需要传入它将要读取和修改的数据结构。例如:

int handleStateStart(
    char c,
    int* current_number,
    char *error_message) 
{
    if( ! isDigit(c)) {
        sprintf(error_message, "Expected a digit at char %d", *offset);
        return STATE_ERROR;
    }
    *current_number = atoi(c);
    return STATE_IN_NUMBER;
}

(这是一种易于理解的状态机实现方式,但还有其他方法可以实现:Is there a typical state machine implementation pattern?)

您的 CSV 解析问题非常适合状态机,并且生成的代码将非常整洁。状态机用于更复杂的解析任务,并且大量用于编译器等事物。在稍后的学习中,您将遇到正则表达式 - 正式地讲,正则表达式是表达消耗字符的有限状态机的一种紧凑方式。

关于c - 读取一串以逗号分隔的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42760417/

相关文章:

c - 实现一个小型图书馆

java - JPanel 和 Frame 之间的默认彩色间距

java - 对字符串不变性的困惑

html - 操作系统错误 : No such file or directory, errno = 2

c++ - 递归算法的实现

将一组偏好与单个结果相匹配的算法?

algorithm - 资源配置-匹配

c - "=="运算符如何在表达式中工作?

c - 在文件系统中存储大量文件

c - 从文本文件中读取一个小的正整数并递增时,结果收到一个大的负数