gpt4 book ai didi

C++:空数组的第一个索引不会用 .resize() 填充其给定字符,但后面的每个其他字符都会

转载 作者:行者123 更新时间:2023-11-30 02:26:31 24 4
gpt4 key购买 nike

我是 C++ 的新手,如果这是基础知识,请原谅我。

下面我有一个基本的加密算法。一切正常,除了字符串“text”的第一个索引的加密输出没有附加到字符串“cipher”之外。第一个索引之后的每个索引都会按原样附加。

对这个有什么想法吗?

代码:

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main()
{
string text = "Do not worry about your difficulties in Mathematics. I can assure you mine are still greater.";
string cipher;

int tSize = text.size();
int cSize = cipher.size();

for (int i = 0; i < tSize; i++)
{
if (isalpha(text[i]))
if (isupper(text[i]))
{
if (text[i] < 'V') cipher.resize(cSize++, text[i] + 4);
else cipher.resize(cSize++, text[i] - 22);
}
else
{
if (text[i] < 'v') cipher.resize(cSize++, text[i] + 4);
else cipher.resize(cSize++, text[i] - 22);
}
else cipher.resize(cSize++, text[i]);
}

cout << cipher << endl;
}

输出

s rsx asvvc efsyx csyv hmjjmgypxmiw mr Qexliqexmgw. M ger ewwyvi csy qmri evi wxmpp kviexiv.

提前致谢!

最佳答案

问题在于变量 cSize 最初为零,并且您在调整 cipher 大小时使用 post 增量。

请记住,后增量会返回 值,即增量之前的值。这意味着第一次调用 resize 会将字符串调整为零。

简单的解决方案是使用 pre 增量,如 ++cSize 所示。或者将cSize初始化为1

关于C++:空数组的第一个索引不会用 .resize() 填充其给定字符,但后面的每个其他字符都会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42758736/

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