问题:字符串在另一个字符串上写入
Problem: String writes over another string
我正在尝试使用以下代码处理两个字符串。结果效果很好,但是每当我尝试为第二个字符串执行相同的操作时,第一个字符串就会按第二个值写入。对于示例,如果第一个字符串=" 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()
方法中可用。
相关文章:
- setlocale的C++土耳其字符串问题
- C++字符串问题-如何访问字符串元素
- 提升,从字符串问题中获得时间
- 字符串问题中的系统( "command" ) 字符串
- 从文件和字符串问题中读取
- 将C++函数转换为 C#(字符串问题)
- 有关字符串C++问题
- Visual Studio和Xcode之间的Chaiscript字符串问题
- 回文字符串问题:为什么我必须放+1而不是-1才能让这个代码工作
- Dll导入Marshal C++字符串问题
- 崩溃:字符串问题
- 正在寻找另一种解决二进制字符串问题的尝试
- C++ Win32 是字符串问题
- 迭代器字符串问题
- Python 3:Python/C API字符串问题
- 带有空格的C++字符串问题
- 有些字符串问题
- C++11 std::regex_replace()创建带有特定字符串问题的regexp
- Turbo C++的字符串问题
- 棘手的子字符串问题