简体   繁体   English

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

[英]Input in Null terminating character array and getting its length

I hava a question.....I have a character array char command[30].我有一个问题.....我有一个字符数组 char 命令[30]。 When I use it for input like if I entered.. on console the after input strlength function must give me length of array equals to 2 as it does not count null character.当我将它用于输入时,就像我在控制台上输入.. 后输入 strlength function 必须给我的数组长度等于 2,因为它不计算 null 字符。 But It is giving me 3 as length of array.但它给了我 3 作为数组的长度。 Why is it happening.为什么会这样。

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

It's probably including the newline character - the Enter key.它可能包括newline - Enter键。

Try this to remove the newine character, then strlen should be as you expect:试试这个删除newine ,然后 strlen 应该是你所期望的:

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

fgets adds the newline character '\n' to the characters you type in, adding an extra character to the length of the string. fgets 将换行符 '\n' 添加到您输入的字符中,在字符串的长度中添加一个额外的字符。 So if you type,, and hit "Enter", the characters ','.因此,如果您键入,并按“Enter”,则字符“,”。 ',', and '\n'. ',' 和 '\n'。 get stored in your command[] array, Thus, the strlen() function returns the length of your string as 3. instead of 2. To fix this, just subtract 1 from the result of the strlen() function, and write a null zero ('\0') to the position where the the '\n' was.存储在您的 command[] 数组中,因此,strlen() function 返回字符串的长度为 3。而不是 2。要解决此问题,只需从 strlen() 函数的结果中减去 1,然后编写 null零('\0')到 position ,其中 '\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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM