【问题标题】:How many characters are in given array but spaces给定数组中有多少个字符但有空格
【发布时间】:2018-12-30 05:58:04
【问题描述】:

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

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

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


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

【问题讨论】:

  • 除了代码要求编译器实现接受空大括号作为有效初始化程序的扩展这一事实之外,我认为呈现的代码中没有任何固有问题。为了有把握地给出答案,我们需要查看证明问题的minimal reproducible example
  • 不过,作为一个疯狂的猜测,尝试在 printf 格式中添加换行符 ("%d\n") 或在 printf 之后刷新标准输出 (fflush(stdout);) 或两者兼而有之。

标签: c arrays if-statement continue


【解决方案1】:

这里很少观察

fgets(c ,256, stdin);

fgets() 存储\n 如果读取在缓冲区的末尾。来自fgets()的手册页

如果读取了newline,则将其存储到缓冲区中。 在最后一个字符之后存储一个终止空字节 ('\0') 缓冲区

首先删除尾随\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] != '\0' ){ /* 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;

}

【讨论】:

  • 您不必删除尾随\n。只需计算 i-k-1 而不是 i-k。
猜你喜欢
  • 2020-01-19
  • 2020-03-22
  • 1970-01-01
  • 2012-10-17
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多