【问题标题】:Why does strlen return different values when the string is given directly and when the string is read?为什么直接给出字符串和读取字符串时strlen会返回不同的值?
【发布时间】:2019-10-07 13:15:29
【问题描述】:

当我直接输入一个字符串时,比如:

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

int main()
{
    char phrase[100] = "lonesomestreet";
    char phrase2[100] = "lonesomestreet";
    printf("String 1 has %d characters, and string 2 has %d characters.\n", strlen(phrase), strlen(phrase2));
    system("pause");
    return 0;

}

返回 14 个字符。 但如果我阅读它们:

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

int main()
{
    char phrase[100];
    char phrase2[100];
    printf("Type a phrase:\n");
    fgets(phrase,100,stdin);
    printf("Type a phrase:\n");
    fgets(phrase2,100,stdin);
    printf("String 1 has %d characters, and string 2 has %d characters.\n", strlen(phrase), strlen(phrase2));
    system("pause");
    return 0;

}

返回 15 个字符。谁能解释一下为什么会这样?

一个补充。如果我计算字符,它也会给出 15:

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

int main()
{
    char phrase[100];
    char phrase2[100];
    printf("Type a phrase:\n");
    fgets(phrase,100,stdin);
    printf("Type a phrase:\n");
    fgets(phrase2,100,stdin);
    int k=0;
    for (int i=0; phrase[i]!='\0'; i++) {
        k++;
    }
    printf("The phrase has %d characters.\n", k);
    system("pause");
    return 0;

【问题讨论】:

标签: c newline fgets strlen


【解决方案1】:

如果目标字符数组中有足够的空间,标准函数 fgets 可以追加换行符。你应该删除它。例如

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

//...

fgets(phrase,100,stdin);

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

或者您可以通过以下方式重写您的 for 循环

size_t i = 0;
while ( phrase[i] !='\0' && phrase[i] != '\n' ) ++i;
printf("The phrase has %zu characters.\n", i);

注意,在尝试输出标准C函数strlen的返回值时,应使用转换说明符%zu而不是%d,因为返回值的类型为size_t

printf("String 1 has %zu characters, and string 2 has %zu characters.\n", strlen(phrase), strlen(phrase2));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多