There are several small errors in your program:
The if
to show the result is switched:
if(chave==0)
printf("O caractere informado existe na string.\n");
else
printf("O caractere informado nao existe na string.\n");
The return that leaves the function is 0
when it does not exist, but in if
the 0
writes that "The given character exists in the string", so you must swap the two printfs
.
The character reading is not correct:
printf("Informe um caractere: ");
scanf("%s",&chave);
If it is a character should be read with %c
, otherwise the program will try to put the terminator \0
because of being string
and will do so in a memory space that does not belong to you, creating a subtle bug, which may appear later.
By switching to %c
will create another problem in relation to the previous reading of scanf("%[^\n]s"
because the line break itself has not been consumed. To solve both without complicating can do so:
scanf(" %c",&chave);
Where space consumes previous line break.
The for
to find the character is also not correct:
for (comp; str[i] != chave; comp--)
{
if(str[i]==chave)
{
return 1;
}
str[i]--;
}
Here the beginning of (comp;
is reductive and does nothing, so you can remove it. Then you use the i
to access the position and fetch the letter then the i
has to increase and not the comp
decrease. Also, you are not considering the case where you do not find the letter in the order condition str[i] != chave
that can leave you wandering the memory infinitely.
Correct would be:
for (; i < comp; i++) {
if(str[i] == chave) {
return 1;
}
}
That makes it even simpler.
See your fixed code working on Ideone
Reinvent the wheel
I know that in C we often actually have to reinvent the wheel, but in your case you are doing it more than would be necessary, and unless it is for educational purposes you should avoid it.
str_length
- There is already a native function to get the size of string
calling for strlen
,
All the logic your program is trying to make to find the first occurrence in a string already exists in the function strstr
To use the two functions I have indicated you need to include <string.h>
, but your program gets much shorter and simpler:
#include <stdio.h>
#include <string.h> //nova inclusão aqui
#define MAX 100
int main() {
char string[MAX];
printf("Digite uma string: ");
scanf("%[^\n]s",string);
int comp = strlen(string); //comprimento com strlen
printf("Comprimento de '%s': %d\n", string, comp);
printf("Informe um caractere: ");
char chave[2];
scanf("%s",chave); //leitura como string pois é necessário para o strstr
if(!strstr(string, chave)) //achar ocorrencia com strstr
printf("O caractere informado nao existe na string.\n");
else
printf("O caractere informado existe na string.\n");
return 0;
}
See also this example in Ideone
Is returning some error?
– rLinhares
@Inhares is not, but if I type for example 'hi' and informs key as 'k', it speaks q is inside the string, ta always informing q this to qlqr key q informo
– flavio