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

How to check the length of an input String in C

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

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] = '[=10=]';
    }
    return;
}

有了这个函数,我可以仅在字符串长于 length 时重复输入。

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

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

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

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) - 1就是SIZE_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] == '[=11=]' && input[length - 2] != '\n') {
  // more data to read.