-1

我想将我作为参数给出的字符串中的每个字符都用一个数字来标记,所以 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;
}
4

1 回答 1

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;
}

否则永远不会被执行。

于 2013-11-08T23:04:11.583 回答