Caesar's cipher

Hello everybody. I've got as homework the coding of Caesar's cipher in C++. I've created the following code. It turns out that the getline function is not working well. Could anyone improve it?

#include <iostream>
#include <string>
using namespace std;
int main()
{
string alphabet= "abcçdeëfghijklmno pqrstuvxyzwABCÇDEËFGHIJKLMNOPQRSTUVXYZW!#$%&'()*+,-./0123456789:;<=>?@[]_{|~}`";
int code[ alphabet.length() ];
for( int j = 0; j < alphabet.length(); j++ )
code[ j ] = j;
cout << "Hello. You can cipher your messages through the following alphabet\n";

for( int c = 0; c < alphabet.length(); c++ )
cout << alphabet[ c ] << ' ';
int continue;
cout << "\nType a number to continue. Press -1 to end: ";
cin >> continue;

while( continue!= -1 )
{
string text;
cout << "Input a message: ";
getline( cin, text);
char cipher[ text.length() ];

int key;
cout << "Input key: ";
cin >> key;
int counter = 0;
for( int i = 0; i < text.length(); i++ )
{
for( int k = 0; k < alphabet.length(); k++ )
{

if( text[ i ] == alphabet[ k ] )
{

cipher[ counter ] = alphabet[ (code[ k ] + key ) % alphabet.length()];
counter++;
}
}
}
if (counter == text.length() )
{
cout << "The cipher text is: ";
for( int l = 0; l < counter; l++ )
cout << cipher[ l ];
}
else
cout << "The preceding text cannot be ciphered" << endl;
cout << "nType a number to continue. Press -1 to end: ";
cin >> continue;
}
}
It turns out that i should use cin.ignore(). But i don't know where to place it.
It turns out that i should use cin.ignore().
No, in your case, it would be way better to use std::ws, as answer by my link indicated;

But i don't know where to place it.
As shown in linked answer, you should place it inside getline (actually between formatted input and getline call)
getline(std::cin >> std::ws, text);
Last edited on
Thank you very much. But i've got another problem though. This code that i've created, doesn't cipher these elements: ç, ë, Ç and Ë. Do you have any idea how to fix it?
This can be problematic. Those characters are not a part of standard character table. Their representation in your source editor and in console can differ.
You can try saving your source file using same encoding your console uses.
Topic archived. No new replies allowed.