我想用一个数字来解析我给出的字符串中的每个字符作为参数,所以a +4 = e等等...... 但不知何故,这个函数只将字符串的最后一个字符分配给我的字符串测试,并且只返回函数末尾的最后一个字符而不进行decalation ...为什么?
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
string code(string, int ) ;
int main() {
int decalage(3);
string worth = "Hello worldas";
string result;
result += code(worth,decalage);
cout << "Resultat :" << result <<endl;
return 0;
}
string code(string worth, int decalage) {
string test;
char bst;
for (char wort : worth) {
if (wort <= 90 && wort>= 65) {
bst = (wort + decalage);
if (bst > 90) {
bst = (bst -90 +64);
test += bst;
}
else {
test+=bst;
}
}
else if (wort >= 97 && wort<=122) {
bst = (wort + decalage);
if (bst > 122) {
bst = (char)((int)bst -122 + 96);
test += bst;
}
else {
test +=bst;
}
}
else {
test +=wort;
}
}
return test;
}
答案 0 :(得分:2)
您应该将两行test += bst;
移到if分支之外。像这样:
std::string code(std::string worth, int decalage) {
std::string test ="";
for (char wort : worth) {
if ((int)wort <= 90 && int(wort)>= 65) {
char bst = (char)((int)wort + decalage);
if ((int)bst > 90) {
bst += (char)((int)bst -90 +64);
}
test += bst;
}else if ((int)wort >= 97 && (int)wort<=122) {
char bst = (char)((int)wort + decalage);
if ((int)bst > 122) {
bst = (char)((int)bst -122 + 96);
}
test += bst;
}else{
test +=wort;
}
}
return test;
}
否则永远不会被执行。