This code is written to identify the position of character in the string from back which matches first with a given character.When i use scanf to get string,the compiler doesn't ask for the character and directly gives the output as 0.I am unable to rectify the problem with scanf.
I ran the function by giving string input directly without scanf and it works fine.
#include<stdio.h>
#include<string.h>
int strrindex(char str[], char t)
{
int n=strlen(str);
while(n>=0)
{
if(str[n]==t)
{
return n;
}
else
{
n=n-1;
}
}
return -1;
}
int main()
{
int k;
char str[100];
printf("enter line\n");
scanf("%s",str);
char t;
printf("enter letter\n");
scanf(" %c",&t);
k=strrindex(str,t);
int p=k+1;
printf("the position is %d",p);
}
The code runs but the output is always 0 mostly because of \n added because of scanf.
You included the return statement
in the while loop
Place it outside the loop.
Pay attention to that the function should be declared like
and return
( size_t )-1in the case when the character is not found because the return type of the standard C functionstrlenissize_t.Bear in mind that there is a similar standard C function
Here is a demonstrative program
Its output is
If you want to exclude the terminating zero from searching then the function can look the following way
In this case the program output is
Also pay attention to that the function
scanfreads a string until a white-space character is encountered.So instead of
scanfusefgets. For example