next up previous
Next: Explanation of the Program Up: A Second C++ Program: Previous: Pseudocode

The real code

Here is the corresponding C++ code. Use your text editor to create the source program. Call the file

Copy the following lines.

#include <iostream>
using namespace std;
int main()
  int age;
  char name[10];

  cout << "enter name and age: \n";
  cin >> name >> age;
  cout << "Your name is " << name
       << " and age is " << age << "\n";

The indentation is not required by the compiler, but it is standard among C++ practitioners for readability. So we require it in this course. Use the emacs Tab key on each line. Notice that emacs knows the conventional format and will indent as shown, except possibly for the next-to-last line.

In your xterm window, compile it with the command

   g++ -o whoyou
If the compilation fails, the error message specifies the line number where the error occurred. Check over and fix the code.

It is a good idea to become familiar with compiler error messages, since they don't always pinpoint the error precisely. So after your compilation succeeds, try deliberately to make the compilation fail. See how the compiler complains if you omit one of the semicolons (a common mistake). See how it complains if you misspell the variable name in one place (another common mistake) or if you leave out one of the declarations (another common mistake).

When the compilation is successful, run your program with the command

You should be prompted for your name and age. Enter them by typing your name as a single word without spaces followed by your age as a single integer and hit the Enter key.

Experiment with various inputs. Try entering your name on one line and age on a second line. Or do a double ``Enter'' between the data items.

Input items translated by the cin class are "words". Words are separated by "white space" (spaces, tabs or ends-of-line). So if you enter your first name and last name with a space between, the first name will be read as your name and the last name will be read as your age, probably not what you wanted.

next up previous
Next: Explanation of the Program Up: A Second C++ Program: Previous: Pseudocode
Carleton DeTar 2008-09-03