为什么这个计算字符串长度的 C 程序会给出错误的输出?

Ary*_*oni 2 c newline fgets string-length strlen

我编写了这个程序,它接受 astring作为输入并返回它的长度。

#include<stdio.h>
#include<string.h>
#define MAX 100

int main()
{
    char a[MAX];
    int len;
    printf("Enter a string: ");
    fgets(a, MAX, stdin);

    len = strlen(a);
    printf("Length of the string = %d", len);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由于该函数strlen()不计算空字符 ie '\0',为什么我的输出总是比输入的字符多 1 string

例如 -

Enter a string: Aryan
Length of the string = 6
Process returned 0 (0x0)   execution time: 4.372 s
Press any key to continue.
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 9

如果提供的数组中有空格,该函数fgets可以将新行字符追加到输入的字符串中。'\n'

来自 C 标准(7.21.7.2 fgets 函数)

2 fgets 函数从stream 指向的流中最多读取比n 指定的字符数少1 的字符到s 指向的数组中。在换行符(保留)之后或文件结束符之后不会读取任何其他字符。在读入数组的最后一个字符之后立即写入空字符

因此在这次呼吁中strlen

len = strlen(a);
Run Code Online (Sandbox Code Playgroud)

新行字符也被计算在内。

您需要将其删除,例如

a[ strcspn( a, "\n" ) ] = '\0';
Run Code Online (Sandbox Code Playgroud)

或者

char *p = strchr( a, '\n' );
if ( p != NULL ) *p = '\0';
Run Code Online (Sandbox Code Playgroud)

  • `a[ strcspn( a, "\n" ) ] = '\0';` 是摆脱 `\n` 的最简单方法。 (2认同)