patterncppModerate
Simple text-to-binary converter written in C++
Viewed 0 times
simplewrittentextbinaryconverter
Problem
I am learning C++ on my own and was hoping for some feedback on this simple text-to-binary converter. The program runs and I haven't encountered any errors with it yet. Any input is welcome.
#include
#include
#include
using namespace std;
int main()
{
char letter = ' ', playAgain = 'y';
string word = " ";
cout binary(letter);
cout > playAgain;
if (playAgain != 'y'){
cout << "\n\nExiting program.";
playAgain = 'n';
}
cin.ignore();
}
return 0;
}Solution
As already mentioned, your code is looking okay. Here are my additions:
-
It's best not to use
-
Variables should be declared/initialized on their own line:
-
You don't need a newline between every line of code. This will just make your program appear longer and harder to read. Just separate lines into groups based on purpose.
-
Variable declarations/initializations should be placed as close in scope as possible to where they will be first used:
-
Your main loop could use
-
Prefer to use
Or if you have C++11, use a range-based
-
It's best not to use
using namespace std.-
Variables should be declared/initialized on their own line:
char letter = ' ';
char playAgain = 'y';-
You don't need a newline between every line of code. This will just make your program appear longer and harder to read. Just separate lines into groups based on purpose.
-
Variable declarations/initializations should be placed as close in scope as possible to where they will be first used:
std::cout << "Please enter a character, word, or phrase: ";
std::string word; // declaration is first used here
getline(std::cin, word, '\n');-
Your main loop could use
for (;;). This is essentially an infinite loop, but it should do a break at the end if the user inputs a value other than 'Y':for (;;)
{
// do stuff
std::cout > playAgain;
std::cin.ignore();
if (playAgain != 'Y')
{
break;
}
// playAgain is 'y', so do stuff again
}-
Prefer to use
std::string::size_type for the inner for-loop as it's the type returned from std::string::size().Or if you have C++11, use a range-based
for loop instead:for (auto iter& : word)
{
letter = iter;
// ...
}Code Snippets
char letter = ' ';
char playAgain = 'y';std::cout << "Please enter a character, word, or phrase: ";
std::string word; // declaration is first used here
getline(std::cin, word, '\n');for (;;)
{
// do stuff
std::cout << "\n\nWould you like to try again? Y/N)";
char playAgain;
playAgain = std::toupper(playAgain);
std::cin >> playAgain;
std::cin.ignore();
if (playAgain != 'Y')
{
break;
}
// playAgain is 'y', so do stuff again
}for (auto iter& : word)
{
letter = iter;
// ...
}Context
StackExchange Code Review Q#2661, answer score: 11
Revisions (0)
No revisions yet.