问题:字符串在另一个字符串上写入

Problem: String writes over another string

本文关键字:字符串 问题 另一个      更新时间:2023-10-16

我正在尝试使用以下代码处理两个字符串。结果效果很好,但是每当我尝试为第二个字符串执行相同的操作时,第一个字符串就会按第二个值写入。对于示例,如果第一个字符串=" fuhg"和第二个字符串等于" ABC"第一个字符串变为:" ABCG"。这可能与内存分配或类似的东西有关,但我无法弄清楚,因为我在那个领域不是很好。

string newPassChar;
string newBloom=bloomFilter(newPass); 
int index=0;
for ( int k =0 ; k < alpha.length() ; k++ )
{
    if (newBloom[k]=='1')
      { 
        newPassChar[index]=alpha[k];
      index++;
      }
}

来自cppreference std :: basic_string :: operator []:

No bounds checking is performed. If pos > size(), the behavior is undefined.

来自cppReference std :: Basic_string Construcor:

1) Default constructor. Constructs empty string (zero size and unspecified capacity).

so:

string newPassChar;

使用size() == 0创建新字符串。

然后:

newPassChar[0] = ...

将覆盖字符串中的空字符。但是在下一个迭代中,当index = 1时,

newPassChar[1] = ....

这是不确定的行为。并产生恶魔。

我认为您想在阅读字符时"推动"字符:

        newPassChar.push_back(alpha[k]);

无需存储另一个用于索引字符串的"索引"变量,字符串对象本身知道它的大小,它可以在size()方法中可用。