对于循环扫描,在c中减少了一个时间 [英] For loop scans one less time in c

查看:84
本文介绍了对于循环扫描,在c中减少了一个时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户输入一个字符串,但在此之前,他输入字符串的大小.然后,我必须阅读并计算每个字母输入了多少次.

The user enters a string of characters, but before that he enter the size of the string. Then I have to read and count how many times each letter is entered.

这是我的代码:

#include <stdio.h>

char ab[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; //Size = 26

int main(void)
{

  int i, j, size, counter[26];
  char temp;

  for(i=0; i<26; i++)
  { 
      counter[i]=0;
  }

  scanf("%d",&size);

  for(i=0; i<size; i++)
  {
    scanf("%c",&temp);

    for(j=0; j<26; j++)
    {
          if(ab[j]==temp)
          {
            counter[j]++;
              break;
          }
      }
  }

  for(i=0; i<26; i++) 
  {
      printf("We have %d %c\n",counter[i],ab[i]);
  }

  return 0;

}

这是我的问题:
在给定的代码中,读取的for循环最后执行一次.因此,例如,如果输入7,即使它从0开始,它也将执行6次而不是7次.您知道问题出在哪里吗?

And here is my problem:
In the given code the for loop that reads executes one last time. So for example if you enter 7 it will execute 6 times instead of 7 even if it starts from 0. Do you know what the problem is?

推荐答案

for(i=0; i<size; i++){

size为7时,

将循环7次.

will loop 7 times when size is 7.

您的问题如下:

您输入一个数字

scanf("%d",&size);

,然后按 Enter .上面的scanf扫描数字并将换行符('\n')留在标准输入流中.在第一个循环的第一次迭代中,

and press Enter. The above scanf scans the number and leaves the newline character('\n') in the standard input stream. In the first iteration of the first loop,

scanf("%c",&temp);

看到换行符并消耗掉换行符,使您认为循环执行的时间减少了1.您可以通过添加

sees the newline character and consumes it thus, making you think that the loop executes 1 less time. You can verify this by adding

printf("Got '%c'", temp);

在循环scanf之后的

.

after the scanf in the loop.

使用

scanf(" %c",&temp);

%c之前的空格会舍弃所有空白字符,直到第一个非空白字符为止都不会包含空白.

The space before %c discards all whitespace characters including none until the first non-whitespace character.

这篇关于对于循环扫描,在c中减少了一个时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆