Linked Questions

Popular Questions

Code does not appear to print concatenated strings correctly

Asked by At

I have some code here where, given a .txt file whose contents is

find replace pre

,I want to find every instance of "pre", and append "k" to it. ie the file should become "find replace kpre".

So I first set out to create a string that is the concatenation of k and pre (assume k and pre are argv[1] and argv[3], respectively)

char appended[1024];
strcpy(appended, argv[1]);
strcat(appended, argv[3]);
printf("appended string is %s", appended); //prints kpre, which is good

char *replaced = replace(buf, argv[3], appended);

//*string is a line in  the file
char* replace(char *string, char *find, char *replace) {
    char *position; 
    char temp[1024];
    int find_length = strlen(find);
    int index = 0;

    while ((position = strstr(string, find)) != NULL) {
        strcpy(temp, string);
        index = position - string;
        string[index] = '\0';
        strcat(string, replace); //add new word to the string
        strcat(string, temp + index + find_length); //add the unsearched 
              //remainder of the string
   return string;


fputs(replaced, temp);

Checking on the console, appended = "kpre", which is correct, but when the code is run the file looks like

find replace kkkkkkkkkkkkkkkk.....kkkkkkk

the k's go on for a while, I cannot see pre when scrolling all the way to the right. I'm having difficulty figuring out why the code doesn't replace the instance of 'pre' with 'kpre', even when the appended variable appears to be correct. I have a feeling it has to do with the fact that I set a 1024 character for temp, but even then I'm not sure why k was copied so many times.

Related Questions