I'm writing a program for my CS class and I need the program to display an * when something is entered that's not a character. I've tried a lot of things bug can't figure it out. Here's my code.....
#include <iostream>
usingnamespace std;
int main ()
{
char target;
cout << "What character would you like to decode?" <<endl;
cin >> target;
while (target != '1')
{
if(target == 'z')
{
cout << "Your decoded character is a. Enter the next character you would like to decode " <<endl<< "or press 1 to stop." <<endl;
}
elseif(target == 'Z')
{
cout << "Your decoded character is A. Enter the next character you would like to decode " <<endl<< "or press 1 to stop." <<endl;
}
else
{
cout << "Your decoded character is " <<static_cast <char> (target + 1) << ". Enter the next character you would like to decode " <<endl<< "or press 1 to stop." <<endl;
}
cin >> target;
}
Could someone please help me out? It's due tomorrow at 11:59 PM and I've been trying to figure this out for over an hour.
Thanks I really appreciate it. If I wanted to had spaces to the cout, how would I go about doing that. To explain more if someone entered in the cin "a b", I would want it to output in the cout "b c" as opposed to "bc", I'd like to include the space in the cout.
If you want to allow the user to enter more than one character, including spaces, then you can't just use a char variable, you'll need to use a char array and use cin.getline() for input. If you just used cin then it would discard everything after the space.
Here's a little program I quickly typed up that does what I think you're asking, it's not complete but if it's what you're looking for you can use it in your program.
int _tmain(int argc, _TCHAR* argv[])
{
constint MAX_SIZE = 51;
char charArray[ MAX_SIZE ];
cout << "Enter a char or chars (50 max): ";
cin.getline( charArray, MAX_SIZE );
for( int i = 0; charArray[ i ] != '\0'; i++ )
{
if( charArray[ i ] == 'z' )
cout << "a";
elseif( charArray[ i ] == 'Z' )
cout << "A";
elseif( charArray[ i ] == ' ' )
cout << " ";
elseif( ! isalpha( charArray[ i ] ) )
cout << "*";
else
cout << static_cast<char>(charArray[ i ] + 1);
}
getch();
return 0;
}
This isn't very good (I just quickly typed it up) so be careful copying it.
All it's doing is reading into the char array ( can be a single char or any number of chars up to 50) and then loops through each char, doing the appropriate checks.
Actually that was exactly what I wanted. The spaces aren't required in the program I just thought if it was something simple I could integrate it in easily but what you're doing is far ahead of where we are. I'm not going to use it in this program but I'm defiantly bookmarking it for reference.
Thanks a lot Mike you've really helped me out a lot.