【问题标题】:How to check the length of an input String in C如何在C中检查输入字符串的长度
【发布时间】:2018-11-06 21:01:55
【问题描述】:

我有这个函数可以检查字符串是否是这样的:

void get_string(char *prompt, char *input, int length)
{
    printf("%s", prompt);                                   
    fgets(input, length, stdin);
    if (input[strlen(input) - 1] != '\n')
    {
        int dropped = 0;
        while (fgetc(stdin) != '\n')
        {
            dropped++;
        }
        if (dropped > 0)
        {
            printf("Errore: Inserisci correttamente la stringa.\n");
            get_string(prompt, input, length);
        }
    }else{
        input[strlen(input) - 1] = '\0';
    }
    return;
}

只有当字符串长于length时,我才能重复输入。

如果我还必须检查字符串是否更短,我该怎么办?

【问题讨论】:

  • @AjayBrahmakshatriya 通过删除末尾的(可能的)换行符来截断字符串。
  • @Someprogrammerdude 我的坏,忽略了条件。谢谢。
  • 您还需要更改您的函数type 以提供有意义的返回来指示成功/失败。 char *get_string(...) 将是一个不错的选择,允许您在出现错误时返回 NULL,否则返回有效指针。您需要检查fgetsreturn - 此时可以生成手册EOF

标签: c string string-length


【解决方案1】:

如果字符串较短,fgets 会处理这个问题。缓冲区不会满,换行符将放在字符串的末尾。

只需检查strlen(input) < length 是否在fgets 之后。如果该条件评估为真,则您读取的字节数少于缓冲区大小可能产生的最大字节数。

【讨论】:

    【解决方案2】:

    OP 的代码受到黑客攻击,可能导致未定义行为

    // What happens if the first character read is a null character?
    fgets(input, length, stdin);
    if (input[strlen(input) - 1] != '\n')
    

    fgets() 读取输入时,输入 空字符 并不特殊。它像任何其他字符一样被读取和保存。

    如果这种病态的情况,input[0] == 0strlen(input) - 1SIZE_MAXinput[SIZE_MAX] 肯定是数组边界之外的访问,因此未定义的行为


    测试fgets() 是否没有读取所有行是将最后一个缓冲区字符设置为非零,然后测试它是否变为0。

    assert(input && length > 1);
    
    input[length - 1] = '\n';
    
    // check `fgets()` return value
    if (fgets(input, length, stdin) == NULL) {
      return NULL;
    }
    
    if (input[length - 1] == '\0' && input[length - 2] != '\n') {
      // more data to read.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 2021-12-13
      • 1970-01-01
      • 2011-12-14
      • 2013-02-06
      • 2015-06-23
      相关资源
      最近更新 更多