jeudi 26 février 2015

First occurrence return with strstr function

Following on from my previous question, it now appears that my code only outputs the first occurrence of cArray from cInput. Is there a way to get strstr to return all of the occurrences instead of stopping the program at the first? Much appreciated.



#include <stdio.h>
#include <string.h>

#define MAX_STR_LEN 120

int main(){
char *cArray[MAX_STR_LEN] = {"example", "this"};
char cInput[MAX_STR_LEN] = "";
char cOutput[MAX_STR_LEN] = "";

printf("Type your message:\n");
for (int y=0; y<1; y++){
fgets(cInput, MAX_STR_LEN, stdin);
char * ptr = cInput;
while((ptr=strstr(ptr, *cArray)) != NULL){
strncpy(cOutput, ptr, strlen(*cArray));
printf("Initialised string array:\n%s\n", cOutput);
ptr++;
}
}
}


Output:



Type your message:
this is an example
Initialised string array:
example
Program ended with exit code: 0

Aucun commentaire:

Enregistrer un commentaire