Amount of Code
Hi all!
Can anybody advise me how to shorten the beneath code? because I always have the idea that my code is way to elaborate. Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <iostream>
#include <windows.h>
using namespace std;
char Convert(char);
int main()
{
SetConsoleTitle("Converting Letters");
char Character = 0;
int Counter = 0;
cout << "Welcome! Enter how many times you want to convert a letter: ";
cin >> Counter;
for(Counter; Counter > 0; Counter--)
{
cout << "Enter a letter: ";
cin >> Character;
cout << "The result is " << Convert(Character) << ".\n";
Character = 0;
}
cin.get();
cin.get();
}
char Convert(char Character)
{
char newCharacter;
switch(Character)
{
case 'a':
newCharacter = 'A';
return newCharacter;
case 'A':
newCharacter = 'a';
return newCharacter;
case 'b':
newCharacter = 'B';
return newCharacter;
case 'B':
newCharacter = 'b';
return newCharacter;
case 'c':
newCharacter = 'C';
return newCharacter;
case 'C':
newCharacter = 'c';
return newCharacter;
//case 'd': ... and so on
default:
cout << "Invalid input...\n";
cin.get();
cin.get();
exit(0);
}
}
|
Your function, Convert, is taking a char and changing the case. So, why not use existing functions to help you?
How about:
1 2 3 4 5 6
|
char Convert(char Character)
{
if (isupper(Character)
{ return tolower(Character); }
else
{ return toupper(Character); }
|
You will still need to check for bad input.
Last edited on
for(Counter; Counter > 0; Counter--)
can change this to
for(; Counter > 0; Counter--)
Can get rid of line 22.
In your function, you can get rid of that variable, and just
1 2
|
return tolower(Character); OR
return toupper(Character);
|
Those functions are in <cctype>
Could also get rid of all those
cin.get()
s
EDIT:
Ninja'd by Moschops! :(
Last edited on
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
// #include <cstdlib> // system()
char convert(char c)
{
if (std::islower(c))
return std::toupper(c);
else
if (std::isupper(c))
return std::tolower(c);
return c;
}
int main()
{
std::string s;
std::cout << "Enter a sentence..." << std::endl;
std::getline(std::cin, s);
std::transform(s.begin(), s.end(), s.begin(), convert);
std::cout << "Result: " << s << std::endl;
// std::system("PAUSE"); // if needed
}
|
Thanks! I didn't know there were existing functions for this.
Topic archived. No new replies allowed.