Entering name

Hello am talking a introductory class on C++. in the lab we have to write a simple piece of code that will ask the user for there name and age. i was able to write the code and it works fine, as long as i only write the first name, eg "john" works great, but "john smith" the code crashes. can someone look at my code and tell me where i am going wrong??

Thank You.

#include <iostream>
#include <string>
#include <conio.h> // to use the system pause cmd "getch()"

using namespace std;


int main()
{
string name;
int age;

// ask their name

cout << "Enter You First Name Please: " << endl;
cin >> name;

// ask the age

cout << "Enter Your age \n" ;
cin >> age;
while (age < 0) // loop if they entered negative age

{
cout << "Sorry you typed in a negative value age, please enter the correct age:" << endl;
cin >> age;
}

cout << "Hello " << name << " Welcome! \n" ;

while (age != 0) // loop excape if they entered zero age
{
if ( age <= 16)
{
cout << "Sorry your are not allowed to drive \n" ;
}
if (16 < age && age < 18)
{
cout << "You can drive,but cannot vote \n" ;
}
else
{
cout << "You are old enough to drive and vote \n" ;
}
break;
}
cout << "\n";
cout << "Thank You " << name << " for using this program" << endl;

getch(); //pause system

return 0;
}
Last edited on
try getline (cin, name); rather than cin>>name;
Last edited on
awesome! thanks you, that worked
When you write
1
2
3
4
5
6
7
cout << "Enter You First Name Please: " << endl;
cin >> name;

// ask the age

cout << "Enter Your age \n" ;
cin >> age;


and enter 2 values, such as john smith, John goes under name, but smith is being assigned to age. Since age is a int, your program crashed.
Topic archived. No new replies allowed.