【发布时间】:2016-09-12 06:24:12
【问题描述】:
底部的当前代码有效,但如果不将 ascii 值移动到我不希望它们出现的位置,我无法组合 if 语句。加密应该只是字母值。大写和小写的 z 应该循环到 A。我有一位老师,但她不知道,所以我会很感激任何帮助。谢谢
这行不通……
if (sentence[i] == 'z' || 'Z')
{
sentence[i] = sentence[i] - 26;
}
这不起作用
if (sentence[i] == 'z' || sentence[i] == 'Z')
{
sentence[i] = sentence[i] - 26;
}
这行得通。
if (sentence[i] == 'z')
{
sentence[i] = sentence[i] - 26;
}
if (sentence[i] == 'Z')
{
sentence[i] = sentence[i] - 26;
}
完整代码。
#include <iostream>
#include <string>
using namespace std;
class EncryptionClass
{
string sentence;
public:
//constructors
EncryptionClass(string sentence)
{setString(sentence);}
EncryptionClass()
{sentence = "";}
//get and set
string getString()
{return sentence;}
void setString(string sentence)
{this-> sentence = sentence;}
//encrypt
void encryptString()
{
for(int i = 0; i < sentence.length(); i++)
{
if (isalpha(sentence[i]))
{
if (sentence[i] == 'z')
{
sentence[i] = sentence[i] - 26;
}
if (sentence[i] == 'Z')
{
sentence[i] = sentence[i] - 26;
}
sentence[i] = sentence[i] + 1;
}
}
}
};
int main()
{
string sentence;
cout << "Enter a sentence to be encrypted. ";
getline(cin, sentence);
cout << endl;
EncryptionClass sentence1(sentence);
cout << "Unencrypted sentence." << endl;
cout << sentence1.getString() << endl << endl;
sentence1.encryptString();
cout << "Encrypted sentence." << endl;
cout << sentence1.getString() << endl;
cin.get();
return 0;
}
【问题讨论】:
-
您声称第二个“不起作用”doesn't hold water。
-
当您尝试
if (sentence[i] == 'z' || sentence[i] == 'Z')时会发生什么让您说它不起作用? -
@slawekwin 我在编译器上尝试时遇到错误。 “赋值时需要左值作为左操作数。”
-
即使我将
if替换为您发布的 second 示例,您发布的完整代码也可以为我正确编译和运行。
标签: c++ string if-statement logical-operators