0

我的代码在这里有一点问题。我只是做了一个小程序来测试我的实际程序。这个想法是用添加变量中的字符串替换所有“(star)here(star)”。但是,当我运行程序时,我的最终答案并不完全正确。这些是我的结果:I_have_a_star_which is super pretty

I_have_a_star_这是超级漂亮。_That_is_great!_I_also_have_a_girlfriend这是超级漂亮

I_have_a_star_ 超级漂亮。_That_is_great!_I_also_have_a_girlfriend 超级漂亮!

任何关于问题可能是什么的想法都将不胜感激。

#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;
}
4

2 回答 2

1

问题是您将字符复制到temp数组中而没有对其进行初始化或 NUL 终止它。因此,当您调用strcat或尝试打印内容时temp多余的垃圾内容可能会搞砸。坚持memset(temp, 0, sizeof(temp)); 在您的while循环之前或将声明更改为temp[500] = "". 或者,您可以temp[j] = '\0';在调用 to 之前strcat和之后添加 then 循环。

于 2012-11-05T04:22:38.430 回答
0

老哥试试这个...

#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;
}
于 2012-11-05T04:27:18.643 回答