简体   繁体   English

代码无法读取字符字符串的最后一个字符(C语言)

[英]Code doesn't read the last character of string of Characters (C language)

#include "stdio.h"
int main() {
  char input[10];
  char standart;
  int i;
  int b = 0;

  scanf("%c", &standart);

  for(i = 0; i < 10; i++){
    scanf("%c ", &input[i]);
    if(input[i] == standart){
      b++;
    }
  }

  printf("%d", b);
  return 0;
}

// ( 2 % a b ( r ) ? ( (

The code is suppost to read the first character in the list, then see how many of said characters there are (not including itself). 该代码是后继代码,可读取列表中的第一个字符,然后查看有多少个上述字符(不包括其自身)。 But the code doesn't read the last character, in short when I input the sample input the code only sees 2 '(' while it should see 3. 但是代码不会读取最后一个字符,总之,当我输入示例输入时,代码只会看到2'(',而应该看到3。

For the given input ( 2 % ab ( r ) ? ( ( , the program takes the first character ( as input to variable standart - 对于给定的输入( 2 % ab ( r ) ? ( ( ,该程序采用第一个字符(作为变量standart输入-

scanf("%c", &standart);

The problem is occurring because in the first iteration of for loop the scanf was reading the first whitespace character (a blank space) from given input that exists after ( and storing it into input[0] . The for loop runs for 10 iterations and the last character ( is not inserted in the input array because of which the standart character count in input array is coming one less than expected ie 2. 之所以会出现此问题,是因为在for循环的第一次迭代中for scanf正在从给定的输入中读取第一个空格字符(空白) (并将其存储到input[0] for 。for循环运行10次迭代,而最后一个字符(未中插入input ,因为其中的阵列standart在字符计数input阵列即将一个小于预期,即2。

Change the for loop scanf statement to - for循环scanf语句更改for -

scanf(" %c", &input[i]); //Removed the space after %c and added a space before %c.

With this, the for loop scanf will eat whitespaces characters. 这样,for循环scanf将吃掉空白字符。 So, the next character from input - 2 will be stored to input[0] and % will be stored to input[1] and so on and the last character '(' will be stored to input[9] . And the b will have the correct standart character count in input array ie 3. 所以,从输入下一个字符- 2将被存储到input[0]%将被存储到input[1]等和最后一个字符“(”将被存储到input[9]而且, b将在input数组中具有正确的standart字符计数,即3。

You have to do it like this scanf(" %c",&c); 您必须像scanf(" %c",&c);
Because it reads '\\n' from previous input, so the space will skip the '\\n' 因为它从先前的输入中读取了“ \\ n”,所以空格将跳过“ \\ n”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM