user1739750
user1739750

Reputation: 37

Replacing words in c string

I'm having a slight problem with my code here. I just made a small little program to test to put into my actual program. The idea is to replace all the "(star)here(star)" with the string in the add variable. However, when I run the program my final answer is not exactly correct. These are my results: I_have_a_star_which is super pretty

I_have_a_star_which is super pretty._That_is_great!_I_also_have_a_girlfriendwhich is super pretty

I_have_a_star_which is super pretty._That_is_great!_I_also_have_a_girlfriendwhich is super prett!

Any ideas on what the problem could be would be much appreciated.

#include<iostream>
#include<string>
#include<string.h>
using namespace std;

int main ( ) 
{
  char array[500] = "I_have_a_star_*here*._That_is_great!_I_also_have_a_girlfriend_*here*!",
  temp[500],
  add[500] = "which is super pretty";
  int i=0, j=0;

  while(array[i] != '\0')
  {
    if(array[i] != '*')
    {
      temp[j]=array[i];
      i++;
      j++;
    }
    else
    {
      strcat(temp,add);
      cout << temp << endl;
      i+=6;
      j+=strlen(add);
    }
  }

  cout << temp << endl;

  return 0;
}

Upvotes: 0

Views: 1433

Answers (2)

Sandy8086
Sandy8086

Reputation: 643

Dude try this...

#include<iostream>
#include<string>
#include<string.h>
using namespace std;

int main ( ) 
{
  char array[500] = "I_have_a_star_*here*._That_is_great!_I_also_have_a_girlfriend_*here*!",
  temp[500],
  add[500] = "which is super pretty";
  int i=0, j=0;

while(array[i] != '\0')
{
  if(array[i] != '*')
  {
    temp[j]=array[i];
    i++;
    j++;
}
else
{
  strcat(temp,add);
  i+=6;
  j+=strlen(add);
 }
}

cout << temp << endl;

return 0;
}

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126203

The problem is that you're copying characters into the temp array without initializing it or ever NUL terminating it. So when you call strcat or try to print the contents of temp extra garbage on the end may screw things up. Stick memset(temp, 0, sizeof(temp)); before your while loop or change the declaration to temp[500] = "". Alternately, you could add temp[j] = '\0'; just before the call to strcat and just after then loop.

Upvotes: 1

Related Questions