Very good.
I have to perform the following exercise: find a word in a sentence, both strings entered by the user. I have done the following:
//i controla posiciones de cadena
//k controla posiciones de palabraCadena
//principio guardará la posicion en la que se encontraría el primer caracter
//palabra guarda la palabra del usuario
//palabraCadena va copiando palabra a palabra de la frase
//encontrado guarda 1 si la palabra ha sido encontrada y 0 si no
void buscarPalabra (char cadena[]){
int i, k=0, principio=0;
char palabra[20];
char palabraCadena[50];
int encontrado=0:
printf("Introdue la palabra que deseas buscar: ");
fflush(stdin);
fgets(palabra,10,stdin);
palabra[strlen(palabra)-1]='\0';
pausa();
printf("BUSCAR PALABRA\n");
printf ("--------------\n");
printf ("Cadena considerada: %s\n", cadena);
printf ("Palabra a buscar: %s\n", palabra);
i=0;
while (i<strlen(cadena)+1){
principio=i;
k=0;
while (cadena[i]!=' ' && cadena[i]!='\0'){
palabraCadena[k]=cadena[i];
i++;
k++;
}
if (strcmp(palabraCadena,palabra)==0){
encontrado=1;
break;
}
i++;
}
if (encontrado==1){
printf ("La palabra se ha encontrado en la posicion %i.\n", principio);
} else {
printf ("La palabra no ha sido encontrada.\n");
}
}
The problem is that when I print what is being saved wordString, it saves my, car, esche, white, ... World, and I don't really understand why. In this way, ''my'' and ''car'' finds them, but everything after this doesn't... For data, I use Dev C++ as the compiler.
Thanks in advance.
From what I see when you finish reading the sentence until the space, you don't restart it, what you can do is restart the word, your word reading cycle would be like this
what it does
memset
is fill the memory space assigned to the word by the character sent, in this case filled by\0
, which in theory would be resetting the variable.memset reference