Sancho Jimenez
Sancho Jimenez

Reputation: 23

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.

Upvotes: 0

Views: 554

Answers (2)

Adam
Adam

Reputation: 33

You have to do it like this scanf(" %c",&c);
Because it reads '\n' from previous input, so the space will skip the '\n'

Upvotes: 1

H.S.
H.S.

Reputation: 12644

For the given input ( 2 % a b ( r ) ? ( (, the program takes the first character ( as input to variable 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 i.e. 2.

Change the for loop scanf statement to -

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. 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 i.e. 3.

Upvotes: 0

Related Questions