直接输入字符串时,例如:
#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;
答案 0 :(得分: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函数%zu
返回的值时,应使用转换说明符%d
而不是strlen
,因为返回的值的类型为{ {1}}
size_t