小编Ary*_*oni的帖子

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

我编写了这个程序,它接受 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)

c newline fgets string-length strlen

2
推荐指数
1
解决办法
396
查看次数

标签 统计

c ×1

fgets ×1

newline ×1

string-length ×1

strlen ×1