Spotting Code Defects #3 (C++ 101)

This is an easy one – something for the C++ 101 kids J

 

When first learning C++ there are some fairly canonical samples people go through.  Hello World, a simple address book, a simple game of adventure, etc.

 

The name/age lookup sample is another one I see a lot.  It’s a great way to learn about console I/O, strings and associative containers.  But even in such simple examples it’s easy to write some bugs.

 

This sample creates a name/age associative mapping.  Then prompts the user for a name.  If the name is known the age will be displayed, otherwise the user will be prompted for the age and the container will be updated.

 

And it works almost all the time!

 

Why such a trivial bug?  Because I’ve seen the defects in production code in the last 5 years.  Sometimes we need to go back to the basics (and it can’t all be buffer overflows and security hacks).  Post comments

 

using namespace std;  is not a defect, by the way.  I’m just keeping the code readable.

 

#include <iostream>

#include <string>

#include <map>

using namespace std;

int main()

{

      map<string, int> people;

      people["johnny"] = 10;

      people["megan"] = 29;

      people["morgan"] = 17;

      while(true)

      {

            string name;

            cout << "Enter a name (or \"quit\" to quit): ";

            cin >> name;

            if(name == "quit")

            {

                  break;

            }

            if(people.find(name) != people.end())

            {

                  cout << name << " is " << people[name] << " years old." << endl;

            }

            else

            {

                  int age;

                  cout << "Adding a new person! Enter " << name << "\'s age: ";

                  cin >> age;

                  people[name] = age;

                  cout << "Added " << name << endl;

            }

      }

}