问题
Description:
I am trying to write a basic program for fun that will input a string/phrase then xor encrypt it and in the end cout the encrypted phrase. I am working on a mac so I will be compiling with xcode and running it in terminal.
Problem:
I am having an error with inputting a string that can be xor encrypted, see code below:
Code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystr;
cout << "What's the phrase to be Encrypted? ";
//getline (cin, mystr);
char string[11]= getline (cin, mystr); //ERROR: Array must be initialized with brace-enclosed initializer
cout << "Phrase to be Encrypted: " << mystr << ".\n";
char key[11]="ABCDEFGHIJ"; //The Encryption Key, for now its generic
for(int x=0; x<10; x++)
{
string[x]=mystr[11]^key[x];
cout<<string[x];
}
return 0;
}
Help:
please identify and explain or provide examples why I am receiving the error code above.
回答1:
You're not calling getline
correctly. You're also trying to use string
as a variable when it's already defined as a type. I'd try something more like this:
getline(cin, mystr);
string result;
for (int i=0; i<10; i++) {
result.push_back(mystr[i] ^ key[i]);
cout << result[i];
}
回答2:
The return type of getline is a stream and you can't assign that to a char array. To initialize an array you have to use:
char s[10] = {'h', 'i', 0};
Or the shorthand for this in case of a char array:
char s[10] = "hi";
In your problem, you'd probably want to use the commented out getline statement and
const char* string = mystr.c_str();
来源:https://stackoverflow.com/questions/23588202/string-input-xor-encryption-program