Newbie ... looping problem
I wrote this basic encrytion program and everything seems to work find until the end of the program when it asks the user if they want to restart the program.
It'll print out, "Enter a string no longer than 20 characters long:"... but it doesn't wait for input... just continues with the program.
Does anyone know what's causing this and how I can fix it?
Code:
#include <iostream.h>
#include <ctype.h>
#include <stdlib.h>
int main()
{
char ans;
do
{
//Declarations
char string[21];
char decrypt;
int i;
//Get string from user
cout<<"Enter a string no longer than 20 characters long:"<<endl;
cin.get(string,20);
cin.ignore(80,'\n');
cout<<endl;
//encrypt
for(int a = 0; a <= 20; a++)
{
if(isupper (string[a]))
i = (int) 'A';
else if(islower ((int) string[a]))
i = (int) 'a';
if(isalpha(string[a]))
{
string[a] = string[a] - i;
string[a] = string[a] + 1;
string[a] = string[a] % 26;
string[a] = string[a] + i;
}
}
//Print out the encrypted string
cout<<"The encrypted string is: "<<string<<endl<<endl;
//Ask for decrypt
cout<<"Would you like to decrypt this string? (y,n) ";
cin>>decrypt;
cout<<endl;
//Decrypt and output
if(decrypt != 'n') //decrypt?
{
for(int j = 0; j <= 20; j++) //decrypt individual characters
{
if(isalpha(string[j]))
{
if(isupper (string[j]))
i = (int) 'A';
else if(islower ((int) string[j]))
i = (int) 'a';
string[j] = string[j] - i;
string[j] = string[j] - 1;
if(string[j] < 0)
string[j] = 25;
string[j] = string[j] + i;
}
}
cout<<endl<<endl<<"The decrypted string is: "<<string<<endl<<endl;
}
//Run again code
cout<< "Would you like to run this program again? (y,n) ";
cin>>ans;
cin.sync();
}while(ans != 'n');
return 0;
}