when I write this code in c it does not work but when I make few changes like replacing with cin and cout it works fine in c
#include <stdio.h>
#include <string.h>
int main()
{
int i=0,l,m;
char str[10],c;
printf("Enter string:");
scanf("%s",str);
printf("Enter character u want to search:");
scanf("%s",c);
l=strlen(str);
while (str[i]){
if (str[i]==c){
m=1;
break;
}
else{
m=0;
}
i ;
}
if (m==1){
printf("Present \n");
}
else{
printf("Not present \n");
}
}
CodePudding user response:
You need to do scanf for a single character as described in this answer.
Just replace scanf("%s",c) with scanf(" %c", &c).
printf("Enter character u want to search:");
scanf(" %c", &c)
CodePudding user response:
The variable c is declared as a single object of the type char
char str[10],c;
So to input data in the object using scanf you have to use the conversion specifier %c instead of the conversion specifier %s that is designated to enter strings and pass the object by reference through a pointer to it
scanf( " %c", &c );
Pay attention to the blank before the conversion specifier %c. It allows to skip white spaces in the input stream.
Also the variable m should be initialized before the while loop like
int i=0,l,m = 0;
And the variable l should be removed because it is in fact not used. The call of strlen is redundant.
And you need to declare variables in minimum scopes where they are used.
The program can look the following way
#include <stdio.h>
int main( void )
{
char str[10] = { 0 };
printf( "Enter string: " );
scanf( "%9s", str );
char c = 0;
printf( "Enter character you want to search:" );
scanf( " %c", &c );
size_t i = 0;
while ( str[i] != '\0' && str[i] != c ) i ;
if ( str[i] != '\0' )
{
printf( "The character %c is present in the string.\n", c );
}
else
{
printf( "The character %c is not present in the string.\n", c );
}
}
CodePudding user response:
Your second scanf is trying to put a string into a single char. (scanf("%s",c); Either scan it as a char or int, or use an array to store the string and then extract the first char from it for your comparison tests.
