4
\$\begingroup\$

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 <iostream> 
#include <string> 
#include <cctype>
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; 
}
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$
  1. The procedure name acronym does not tell you what this procedure is doing. Naming it create_acronym would make the code more obvious.

  2. 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

  3. Most times acronyms are capitalized. You might want to capitalize each letter before adding it to the phrase.

  4. 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.

  5. 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.

\$\endgroup\$
1
\$\begingroup\$
  • Correctness

    The code doesn't seem to handle spans of spaces; it doesn't handle tabs and other whitespace characters.

  • Style

    • using namespace std is bad practice
    • It is good that you #include <cctype>, now you shall make use of it. For example, isspace is your friend.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.