【发布时间】:2021-02-06 02:25:44
【问题描述】:
这里是初学者。我试图在不使用 strlen() 函数的情况下获取输入字符串的长度。我编写了一个程序,计算输入字符串中存在的每个字符,直到它到达空终止符(\0)。
运行程序后,我能够计算出第一个单词的长度,但不能计算整个句子的长度。 示例:当我输入“你好,你好吗?”时,它只计算字符串的长度直到“你好”,空格后面的其他字符被忽略。我想让它计算整个句子的长度。
下面是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
char str1[100];
int i = 0;
int count = 0;
printf("Enter the string you want to calculate (size less than %d)\n", 100);
scanf("%s", str1);
while (str1[i] != '\0') //count until it reaches null terminator
{
++i;
++count;
}
printf("The length of the entered string is %d\n", count);
return 0;
}
【问题讨论】: