在C语言中,用户如何找到输入行中的空格数?

在C语言中,用户如何找到输入行中的空格数?,c,space,C,Space,我想知道如何检测用户输入的行中的空格数?我正在使用的scanf功能是: scanf (" %[^\n]s", &line[0]) 这里的line是我的char变量 我做错了什么吗?这是计算空格的方法,因为您成功地读取了输入: uint spaces = 0; size_t len = strlen(line); for (size_t idx=0; idx<len; ++idx) if (line[idx] == ' ') ++spaces; uint空格=0

我想知道如何检测用户输入的行中的空格数?我正在使用的
scanf
功能是:

scanf (" %[^\n]s", &line[0])
这里的
line
是我的
char
变量


我做错了什么吗?

这是计算空格的方法,因为您成功地读取了输入:

uint spaces = 0;
size_t len = strlen(line);
for (size_t idx=0; idx<len; ++idx)
   if (line[idx] == ' ')
      ++spaces;
uint空格=0;
尺寸长度=标准长度(直线);

对于(size_t idx=0;idx,以下程序将打印字符串中的空格数

    #include<stdio.h>
    void main(void)
    {
        char *input_string;
        unsigned int space_counter = 0;
        scanf("%[^\n]",input_string);
        while(input_string != '\0')
        {
           if(*input_string == ' ')//check whether the char is space
              space_counter++      //increment space counter

           input_string++;         //increment counter
        }
        printf("Number of spaces in the string=%d",space_counter);
    }
#包括
真空总管(真空)
{
字符*输入字符串;
无符号整数空间\计数器=0;
scanf(“%[^\n]”,输入字符串);
while(输入字符串!='\0')
{
if(*input_string=='')//检查字符是否为空格
空格_计数器+++//递增空格计数器
输入_string++;//递增计数器
}
printf(“字符串中的空格数=%d”,空格\u计数器);
}

除了我可以驾驶卡车通过的缓冲区溢出漏洞之外,否:-)使用strlen不是很有效。如果您的字符串长度为n,strlen将被调用n次。@MichaelWalz是的,但我已经写了一个快速的答案,现在它得到了改进
    #include<stdio.h>
    void main(void)
    {
        char *input_string;
        unsigned int space_counter = 0;
        scanf("%[^\n]",input_string);
        while(input_string != '\0')
        {
           if(*input_string == ' ')//check whether the char is space
              space_counter++      //increment space counter

           input_string++;         //increment counter
        }
        printf("Number of spaces in the string=%d",space_counter);
    }