I was writing a function for finding character from a given string:
Test.c file is as follows:
#include<stdio.h>
int findIndex(char *array, char search)
{
int count=0;
char test;
int check = 0, repeat;
if(search == ',')
repeat = rand()%10;
else
repeat = rand()%11;
while((test = array[count]) != NULL)
{
if(test == search)
{
if(check == repeat)
return count;
check++;
}
count++;
}
}
int main()
{
char sc[] = "cn:Y,x509UniqueIdentifier:Y,pseudonym:Y,name:Y,l:Y,street:Y,state:Y,postalAddress:Y,postalCode:Y,telephoneNumber:Y,emailAddress:Y";
char testchar;
printf("Enter the search character: ");
testchar = getc(stdin);
printf("The search char found at: %d position.\n",findIndex(sc,testchar));
fflush(stdin);
while(testchar != 'N')
{
printf("The search char found at: %d posotion.\n",findIndex(sc,testchar));
printf("Enter the search character: ");
scanf("%c",&testchar);
fflush(stdin);
}
return 0;
}
The expected output was the index of character only one time, but I am getting this:-
[amarjeet@amarjeet ~]$ ./a.out
Enter the search character: Y
The search char found at: 66 position.
The search char found at: 128 position.
Enter the search character: The search char found at: 0 position.
Enter the search character:
Where did I go wrong? Please let me know what is the issue and how to solve it.
You have one warning in your code which must be corrected
The above line generates warning: comparison between pointer and integer.Therefore should be corrected as
In your output you are getting the index of character twice because newline character is also taken and its position is also getting printed(As you are pressing enter).
To avoid this you can do this
Thats it your program works now.
Note:Use of fflush(stdin)is considered a bad practice and has undefined behaviour.Its better not to use it for flushing input streams as its unportable.See this more information Do not use fflush(stdin)
Output
Hope it helps.Happy Coding!!