以下程序尝试加密字符串并保存到文本文件中,然后打开文件,解密并显示消息。
这是代码 -
private: System::Void saveToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
SaveFileDialog^ dlg = gcnew SaveFileDialog();
dlg->Filter = "Text Files|*.txt";
char key = 'a';
if(dlg->ShowDialog()==Windows::Forms::DialogResult::OK)
{
String^ stream = txtOutput->Text;
char* num = new char[stream->Length];
char* xorchar = (char*)(void*)Marshal::StringToHGlobalAnsi(stream);
int i=0;
for(i=0;i<stream->Length;++i){
num[i] = *xorchar ^ key;
*xorchar++;
}
num[i] = '\0'; //add trailing NULL
//Marshal::FreeHGlobal((System::IntPtr)(void*)xorchar); THIS WAS GIVING AN ERROR, NOT SURE WHY
String^ save = gcnew String(num);
System::IO::File::WriteAllText(dlg->FileName, save);
}
}
private: System::Void openToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
OpenFileDialog^ dlg = gcnew OpenFileDialog();
dlg->Filter = "Text Files|*.txt";
String^ stream;
char key = 'a';
if(dlg->ShowDialog()==Windows::Forms::DialogResult::OK)
{
stream = System::IO::File::ReadAllText(dlg->FileName);
char* num = (char*)(void*)Marshal::StringToHGlobalAnsi(stream);
int i=0;
for (i=0;i<stream->Length;++i)
{
num[i] = num[i] ^ key; //DECRYPT
}
String^ orig_stream = gcnew String(num);
txtOutput->Text = orig_stream;
}
}
现在的问题是,当我输入一个字符串时,它只适用于不等于键的字符。 例如,设键='a'
例如:INPUT:“我喜欢这个”//这将正确解密。
INPUT:“我喜欢苹果”//只有'我喜欢'会解密,休息不会出现。
即,如果遇到字符'key'(在本例中为'a'),它将停止解密。
感谢任何帮助。谢谢!
答案 0 :(得分:3)
与自身xor'd的值将始终产生0. A 0 char
也称为空终止符(0 == '\0'
)。 C ++中的字符串是以空值终止的,也就是说它们在空终止符处停止。
简单示例:
#include <iostream>
int main(){
char str[] = "hi there!\0this will not get printed.";
std::cout << str;
}