strlen统计字符串长度包含换行符,但不包含结束符‘\0’,
输入三个字符123,加上换行符是4个,我的这个count为啥是11
#include
#include
int main(void)
{
char str[256];
int count = 0;
printf("input string to str:");
int i = 0;
do
{
scanf("%c", &str[i]);
} while (str[i] != '\n' && ++i);
count = strlen(str);
printf("%d",count);
return 0;
}#include
#include
int main(void)
{
char str[256];
int count = 0;
printf("input string to str:");
int i = 0;
do
{
scanf("%c", &str[i]);
} while (str[i] != '\n' && ++i);
count = strlen(str);
printf("%d",count);
return 0;
}
str没有初始化,按字符输入后没有给字符串结束符'\0'
strlen是会一直计数到字符串数组中的'\0'。
你可以输出str看看,输出会比123要多。
你这个do while
有点多余吧
没看错的话你想一个个输入
char str[256];
int count = 0;
printf("input string to str:\n");
int i = 0;
scanf("%s", str);
while (str[i] != '\n' && ++i)
{
}
count = strlen(str);
printf("%d", count);