Venu
Venu

Reputation: 11

How to read string followed by character in c?

#include<stdio.h>
int main() {
   char *str, ch;
   int count = 0, i;

   printf("\nEnter a string : ");
   scanf("%s", str);

   printf("\nEnter the character to be searched : ");
   scanf("%c", &ch);

   for (i = 0; str[i] != '\0'; i++) {
      if (str[i] == ch)
         count++;
   }

   if (count == 0)
      printf("\nCharacter '%c'is not present", ch);
   else
      printf("\nOccurence of character '%c' : %d", ch, count);

   return (0);
}

while i executing this code the string is taken after that it will not taking any characters and showing results.

Upvotes: 1

Views: 1035

Answers (3)

luddbro
luddbro

Reputation: 85

Defining a max length would be the simplest way to solve this. Insted of using scanf, I would recomend using fgets as done below. It is much more failsafe since you can define the max number of characters to be read. Tutorialspoint's explanation of fgets

#define MAX_LENGTH 100

int main() {
   char str[MAX_LENGTH], ch;
   int count = 0;

   printf("\nEnter a string : ");
   fgets(str, MAX_LENGTH, stdin);

   printf("\nEnter the character to be searched : ");
   scanf("%c", &ch);

   ...

}

Upvotes: 0

vishalknishad
vishalknishad

Reputation: 734

Always write scanf like this, to read the previous newline character:

printf("\nEnter the character to be searched : ");
scanf(" %c", &ch);

OR

use getchar()

printf("\nEnter the character to be searched : ");
getchar();
scanf("%c", &ch);

Upvotes: 0

CIsForCookies
CIsForCookies

Reputation: 12817

Your code might crash (happened to me when verifying it on my machine) because you did not allocate space for str... you should change char *str, ch; to something like char *str = malloc(100), ch;

Also, change scanf("%c", &ch); to scanf(" %c", &ch); to resolve your problem. This happens because when you enter your string, you end it with enter, and that enter is consumed by your next scanf(%c) and so, your second scanf() only reads the enter instead of reading the char you intend. scanf(" %c", &ch); will ignore all whitespaces, including the previously entered enter :-) and wil allow your char to be processed

Upvotes: 1

Related Questions