gpt4 book ai didi

c++ - 退出循环时字符串的内容发生变化

转载 作者:太空狗 更新时间:2023-10-29 23:42:34 25 4
gpt4 key购买 nike

我有一个简单的函数,它检查给定的字符串是否符合特定条件,然后根据作为参数收到的 2 个字符串生成第三个字符串。第三个字符串很好,但是当我返回它时,它突然变成了“\n”。

string sReturn = "";
if (sText.size() != sPassword.size()) {
//Checks to see if the texts match a condition
return sReturn;
}
for (int foo = 0; foo < sText.size(); foo++) {
sReturn = "";
sReturn += (char)sText[foo] ^ (char)sPassword[foo];
}
return sReturn;

在 for sReturn 中很好并且有正确的内容,但是一旦它存在循环,调试器突然告诉我它的内容是“\n” .我做错了什么?

最佳答案

  1. 你不必初始化字符串使用空字符数组,如:

    std::string sReturn = "";

    Default constructor打算这样做对你来说效率更高。正确代码:

    std::string sReturn;
  2. 将空字符串分配给 sReturn在循环中的每次迭代中不正确。更不用说清除你必须调用的字符串 std::string::clear () :

    sReturn = "";

    正确的代码:

    sReturn.clear (); 

    但这应该从在你的情况下循环。

  3. 不需要明确说明转换运算符 [] 的结果(size_t) 变成一个字符,因为它是一个字符:

    sReturn += (char)sText[foo] ^ (char)sPassword[foo];

    正确的代码:

    sReturn += sText[foo] ^ sPassword[foo];
  4. 使用 post-increment为了循环是没有必要的。它使一个每个“foo”的额外拷贝增量:

    for (int foo = 0; foo < sText.size(); foo++)

    这可能会被优化编译器,但你必须摆脱这个坏习惯。使用 pre-increment反而。正确的代码:

    for (int foo = 0; foo < sText.size(); ++foo)
  5. 调用 std::string::size ()字符串大小时的每次迭代不改变是没有效率的:

    for (size_t foo = 0; foo < sText.size(); ++foo)

    更好的代码:

    for (size_t foo = 0, end_foo = sText.size(); foo < end_foo; ++foo)

    注意size_t类型。你不能存储32 位有符号整数的字符串大小因为它没有足够的能力存储大量。正确的类型是size_t,由返回std::string::size () 方法。

考虑到以上所有因素,正确的函数应该是这样的:

std::string
getMixedString (const std::string & text, const std::string & password)
{
std::string result;
if (text.length () != password.length ())
return result;
for (size_t pos = 0, npos = text.length (); pos < npos; ++pos)
result += text[pos] ^ password[pos];
return result;
}

但是如果你希望最终的字符串是人类可读的,那就有问题了。使用eXclusive OR两个 ASCII 上的 (XOR) 运算符字符可能会或可能不会为您提供人类可读的字符,甚至是 ASCII特点。因此,您最终可能会得到包含换行符、不可读字符、一些 garbage 的结果字符串。无论如何。

要解决这个问题,您必须想出一些更好的算法来根据其他两个字符串生成一个字符串。例如,您可以使用 MD5两个字符串的哈希值或在 base64 中对它们进行编码.

祝你好运!

关于c++ - 退出循环时字符串的内容发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3532493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com