Need to get name and age from the user in a specific format

Viewed 28

I'm trying to get the specific output of

What is your name?
What is your age?
Hello, Mr. Alex Whatmore (35)! 

This is my code:

#include <iostream>
using namespace std;
#include <string>


int main()
{ 
  string name;
  int age;

  cout<<"What is your name?";
  cin>>name;
  cout<<"What is your age?";
  cin>>age;
  cout<<"Hello,"<<name;
  cout<<age;
  cout<<"!";
return 0;
}

How could I put the numbers in brackets or how could I allow the user to input their first and last name?

1 Answers

Every time you ask your user for input, expect him or her to press Enter.

#include <ciso646>
#include <iostream>
#include <limits>
#include <string>

int main()
{
  std::string name;
  int         age;

  std::cout << "What is your name? ";
  getline( std::cin, name );

  std::cout << "What is your age? ";
  std::cin >> age;
  std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

  if (!std::cin or name.empty() or (age < 0) or ...)
  {
    complain about bad input
  }

  std::cout << "Hello " << name << " (" << age << ")!\n";
}

For homework assignments you can often assume that all input will be correct and leave off any checks.

  • !std::cin will be true if the user tried to input anything but a valid integer for age, or if EOF was reached before all your inputs were complete.
  • name.empty() doesn’t preclude the user from entering a bunch of spaces or dashes or anything weird for his name.
    You don’t need to care for a homework solution, but Patrick McKenzie’s Falsehoods Programmers Believe About Names should be required reading for anyone serious about dealing with identifying people with computer systems.
  • Obviously, people cannot be younger than zero years old.
  • Et cetera.

The numeric_limits thing is obnoxiously verbose, but it is how C++ expects you to skip to NL. A more correct way would be to get input as a string and then attempt to convert the entire string to int and complain on failure. The exampled method lets the user enter any random stuff after a valid integer (which we just ignore with the cin.ignore(...)).

Again, for a simple homework, I’d let it slide.

Related