I believe the code below is about ideal for learning how to do this kind of nearly-first C++ program.
The little technical problem with your code was just that double
is keyword, not a name defined by the standard library, and hence, not in namespace std
.
In addition I’ve added
inclusion of the <string>
header, necessary for using std::string
in a portable way,
a using namespace std;
directive, very handy for small exploration programs (but do not place this in the global namespace in a header file!),
checking of whether input operations succeed (also output can fail but that’s extremely rare).
The way that I check for input operation failure, using boolean "or" (the ||
operator), is not yet very much used in C++, but is common in some other languages. Essentially the left hand argument of ||
is converted to bool
, since that’s what ||
requires. The left hand argument is the expression result of some input operation, which in general is a reference to the cin
stream, and a bool
value is then produced via a defined conversion that is equivalent to writing !cin.fail()
(where !
is the logical "not" operation).
E.g., getline( cin, first ) || fail( ... )
reads very nicely as “getline
or else fail
”, and in addition to reading nicely it’s also visually distinctive, easy to recognize as a failure check.
#include <iostream>
#include <string>
#include <stdlib.h> // exit, EXIT_FAILURE
using namespace std;
// Poor man's way to handle failure, but good enough here:
bool fail( string const& message )
{
cerr << "!" << message << endl;
exit( EXIT_FAILURE );
}
int main()
{
cout << "Please enter your first name: ";
string first;
getline( cin, first )
|| fail( "Sorry, input of your first name failed." );
cout << "Please enter your last name: ";
string last;
getline( cin, first )
|| fail( "Sorry, input of your last name failed." );
cout << "Please enter your age in years: ";
double age;
cin >> age
|| fail( "Sorry, input of your age failed." );
cout << "Hello, " << first << " " << last << "." << endl;
cout
<< "Your age is " << age << " years"
<< " and you are "<< (age*12) << " months old."
<< endl;
}