C- While循环不起作用

0 c while-loop

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

int main(void)
{
    char str1[1000];
    int i, letter, space = 0;
    char ch = str1[i];

    printf("Enter a sentence: ");
    scanf("%[^\n]s", str1);
    printf("you enter %s\n", str1);

    while (i != strlen(str1)) {
        if (ch != ' ') {
            letter++;
        } else if (ch = ' ') {
            space++;
        }
        i++;
    }
    printf("%d %d", letter, space);
}
Run Code Online (Sandbox Code Playgroud)

我的while循环不起作用,我似乎无法找到问题.我在ubuntu中使用终端,在打印用户字符串后,我得到一个空行.我必须使用Ctrl-Z来停止脚本.

Wea*_*ane 7

我看到的错误:使用未初始化的变量 - 局部变量不会自动初始化.

另一个是你不从循环中的字符串中读取字符.

第三是不必要的和语法不正确if (ch=' '),应已if (ch==' ')

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

int main(void){
    char str1[1000];
    int i = 0, letter = 0, space = 0;       // initialise all to 0;

    printf("Enter a sentence: ");
    scanf("%[^\n]s",str1);
    printf("you enter %s\n",str1);

    while (i!=strlen(str1)){
        char ch = str1[i];                  // move this inside the loop
        if (ch!= ' '){
            letter++;
        }else {                  // unnecessary - you already checked space
            space++;
        }
        i++;
    }
    printf("%d %d\n", letter, space);
}
Run Code Online (Sandbox Code Playgroud)

计划会议:

Enter a sentence: hallo my friend
you enter hallo my friend
13 2
Run Code Online (Sandbox Code Playgroud)