计算字符串数组的长度时,空格后输入的任何字符串字符都将被忽略

时间:2021-02-06 02:25:44

标签: c string

这里是初学者。我试图在不使用 strlen() 函数的情况下获取输入字符串的长度。我编写了一个程序,它计算输入字符串中存在的每个字符,直到它到达空终止符 (\0)。

运行程序后,我能够计算出第一个单词的长度,但不能计算整个句子的长度。 示例:当我输入“你好,你好吗?” ,它只计算字符串的长度,直到“hello”,空格后的其他字符被忽略。我想让它计算整个句子的长度。

下面是我的代码。

#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;
}

2 个答案:

答案 0 :(得分:2)

%s 格式说明符读取字符直到第一个空白字符。所以你一次只能读一个字。

改为使用 fgets,它一次读取整行文本(包括换行符)。

答案 1 :(得分:0)

像这样修改代码,问题就解决了。

LinkedList::ListNode