【问题标题】:Clarification in getop()getop() 中的说明
【发布时间】:2015-05-12 07:15:27
【问题描述】:

在 Dennis Ritchie 的《C 编程语言》一书中, 在 getop 函数中, 他说 s[1]='\0' 为什么他在索引 1 处结束数组?有什么意义和需要?

在后面的部分中,他确实使用了数组的其他部分..

int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';

    if (!isdigit(c) && c != '.')
        return c; /* not a number */

    i = 0;
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()))
            ;

    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';

    if (c != EOF)
        ungetch(c);

    return NUMBER;
}

【问题讨论】:

  • 请正确缩进您的代码。
  • 感谢 RedX 现在缩进了
  • while ((s[0] = c = getch()) == ' ' || c == '\t'); 这样的行让我想哭。
  • @ammoQ 确实如此。然后人们仍然推荐K&R,我完全不知道为什么。看这可怕的代码,不是OP写的,是K&R写的!如果今天有任何菜鸟程序员写出这样的代码,他会立即被解雇。
  • @ammoQ 也不教任何人正确的编程,也不校对或审查他们自己的工作......

标签: c kernighan-and-ritchie


【解决方案1】:

因为函数可能会在剩余的输入被读取之前返回,然后s 需要是一个完整的(和终止的)字符串。

【讨论】:

  • 哦。如果没有输入??
【解决方案2】:

稍后将覆盖零字符,除非测试 (!isdigit(c) && c != '.') 是否为真,以便函数提前返回。顺便说一句,一些编码指南会阻止从函数中间返回。

只有当函数提前返回时,s[1] = '\0' 才相关。因此,可以编码

int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;

    if (!isdigit(c) && c != '.')
    {   
         s[1] = '\0'; /* Do this only when we return here */
         return c; /* not a number */
    }
    i = 0;
    if (isdigit(c)) /* collect integer part */
    /* ... */

代码很简洁。这些人知道他们的语言和算法。但是 sn-p 缺少错误处理,因此依赖于正确的输入(无效的输入可能让s 为空或让s 溢出)。

这并非不典型。有效数据的处理通常简单明了;处理所有突发事件会使代码变得复杂和巴洛克。

【讨论】:

    【解决方案3】:

    s[] 可能只是一个数字操作数,如“+”、“-”等。

    在这种情况下,s[1] 必须是 '\0' 才能让 s 成为正确的字符串。

    【讨论】:

      猜你喜欢
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2019-03-22
      • 2020-07-24
      • 2015-10-10
      • 2013-05-01
      • 2013-07-13
      相关资源
      最近更新 更多