c - 如何在C中检查输入字符串的长度

标签 c string string-length

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

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 时,我才能使用此函数重复输入。

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

最佳答案

如果字符串较短,fgets照顾那个。缓冲区不会满,换行符将放在字符串的末尾。

简单地检查是否strlen(input) < lengthfgets 之后.如果该条件评估为真,则您读取的字节数少于缓冲区大小允许的最大字节数。

关于c - 如何在C中检查输入字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50563472/

相关文章:

java - 输出文本文件中最长的单词

c - 如何使用 'c' 语言中的 extern 关键字访问在其他文件中声明的结构

c - 下面这段代码是干什么的

c - 为什么我应该使用或不使用 MSG_CONFIRM?

c - c 编程中的字符串在输出末尾具有垃圾值

php - 字符串到数组的转换、array_rand、取消设置以及返回数组到字符串。有捷径吗?

python - 如何返回给定长度的所有列表元素?

c - Arduino 系列在 Debian 上运行良好,但在 Raspbian 上挂起

C#:将变量插入文本文件

c - 使用 malloc 分配时是否包含空字符