snippetcppMinor
Prompt user for input then create an acronym from it
Viewed 0 times
fromcreateuserinputforthenacronymprompt
Problem
My program is complete and working, but I would like second opinions on it. The program prompts the user to enter something like a phrase or some words. Then it will create an acronym of what was entered. What are some adjustments I can make to my program to make it more efficient?
#include
#include
#include
using namespace std;
string acronym(string str);
int main()
{
string str;
while (true)
{
cout << "\nPlease enter a string: ";
getline(cin, str);
if (str == "")
{
break;
}
cout << "\n\nThe acronym is \"" << acronym(str) << "\"" << "\n";
}
system("PAUSE");
return 0;
}
string acronym(string str)
{
string phrase = "";
phrase = str[0];
for (int i = 0; i < str.length(); i++)
{
if (str[i] == ' ')
{
phrase += str[i+1];
}
}
return phrase;
}Solution
-
The procedure name
-
Error checking: You assume that the user only enters a single space between words. This will cause problems if the user enters more than one space by accident, introducing spaces in your acronym
-
Most times acronyms are capitalized. You might want to capitalize each letter before adding it to the
-
With renaming your procedure
-
Pausing execution: Some say using
The procedure name
acronym does not tell you what this procedure is doing. Naming it create_acronym would make the code more obvious.-
Error checking: You assume that the user only enters a single space between words. This will cause problems if the user enters more than one space by accident, introducing spaces in your acronym
-
Most times acronyms are capitalized. You might want to capitalize each letter before adding it to the
phrase.-
With renaming your procedure
create_acronym, you can rename the phrase variable to acronym, which is more appropriate since an acronym is not a phrase. A phrase is one or more words.-
Pausing execution: Some say using
system("PAUSE") is bad. Instead, just read from cin to a variable and discard the value. That way the application will hang waiting for input until the user presses the ENTER key.Context
StackExchange Code Review Q#102002, answer score: 4
Revisions (0)
No revisions yet.