在 Null 终止字符数组中输入并获取其长度

问题描述

我有一个问题.....我有一个字符数组char命令[30]。当我使用它进行输入时,就像我输入一样!!在控制台上,输入后的 strlength 函数必须给我等于 2 的数组长度,因为它不计算空字符。但它给了我 3 作为数组长度。为什么会这样。

    char command[30];
    fgets(command,30,stdin);
    printf("%zu",strlen(command));

解决方法

它可能包含 newline 字符 - Enter 键。

尝试删除 newine 字符,然后 strlen 应该如您所愿:

command[strcspn(command,"\n")] = 0;

,

fgets 将换行符 '\n' 添加到您输入的字符中,并为字符串的长度添加一个额外的字符。所以如果你输入!!然后按“Enter”,字符 '!'、'!' 和 '\n' 将存储在您的 command[] 数组中。因此,strlen() 函数将字符串的长度返回为 3,而不是 2。要解决此问题,只需从 strlen() 函数的结果中减去 1,然后将空零 ('\0') 写入'\n' 所在的位置。

#include <stdio.h>
#include <string.h>

int main(void)
{
    char command[30];
    
    printf("Enter text: ");

    fgets(command,30,stdin);

    int length = strlen(command);

    command[length - 1] = '\0';

    printf("String length is %lu\n",strlen(command));

    return 0;
}