给定数组中有多少个字符但有空格

How many characters are in given array but spaces

我试图找出给定数组中除空格外的字符数 但它不起作用,k 应该计算空白并从 i[characters + blanks] 中减去它们,但它没有。

int i= 0;
int n= 0;
int k= 0;
char c[256] = {};
fgets(c ,256, stdin);

while(c[i] != '[=10=]' ){
     if(c[i] == ' '){
             i++;
             k++;
             continue;}
i++;}


printf("%d",i-k);

很少观察,这里

fgets(c ,256, stdin);
如果读取,

fgets()\n 存储在缓冲区的末尾。来自 fgets()

的手册页

If a newline is read, it is stored into the buffer. A terminating null byte ('[=17=]') is stored after the last character in the buffer

先删除尾随 \n,然后对其进行迭代。例如

fgets(c, sizeof(c), stdin);
c[strcspn(c, "\n")] = 0; /* remove the trailing \n */ 

此处也不需要使用 continue,即您可以在不使用它的情况下完成任务。例如

int main(void) {
        int i= 0;
        int k= 0;
        char c[256] = ""; /* fill whole array with 0 */
        fgets(c, sizeof(c), stdin);
        c[strcspn(c, "\n")] = 0; /* remove the trailing \n */
        while(c[i] != '[=12=]' ){ /* or just c[i] */
                if(c[i] == ' ') {
                        k++; /* when cond is true, increment cout */
                }
                i++; /* keep it outside i.e spaces or not spaces 
                        this should increment  */
        }
        printf("spaces [%d] without spaces [%d]\n",k,i-k);
        return 0;

}