HELP (Name, age and adress)

I'm new with C++ :(

Im trying to create a program that will allow the user to enter name that accepts first and last name (or more than 1 words) and as well as in address. And enter name that will not allow any characters which only accepts number/s.

Here's my codes below:

#include <iostream>
#include <string>

using namespace std;

int main(){
string name;
char address[100];
int age=0;

cout << "Enter your Name: ";
getline(cin,name);

cout << "Enter your Age: ";
cin >> age;

cout << "Enter your Address: ";
cin >> name;


cout << "\nName:" <<name <<endl;
cout << "Age:" <<age <<endl;
cout << "Address:" <<address <<endl;

return 0;
}

- Name is working.
- Age: when I input letters it will directly show the Output and not able to enter the address.
_______________________________________
Output sample:

Enter name: Elliot Smith
Enter age: e
Enter your address:

Name: Elliot Smith
Age: 0
Address: ╕■>
_______________________________________

- However if I enter the right number the problem in the address area is that it will only accepts 1 word like if i enter New York it will only shows new.


CAN ANYONE HELP ME CORRECT MY CODES?
Thanks in advance.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
string name, address, age;


cout << "Enter your Name: ";
getline(cin,name);

cout << "Enter your Age: ";

int myNumber = 0;

 while (true) 
 {
   getline(cin, age);

   // This code converts from string to number safely.
		stringstream myStream(age); // requires #include <sstream>
	if (myStream >> myNumber)
     break;
   cout << "Invalid Request, please enter a number" << endl;
 }

cout << "Enter your Address: ";
getline(cin, address);

cout << "\nName: " << name << endl;
cout << "Age: " << age << endl;
cout << "Address: " << address << endl;

system("pause");
return 0;
}


I'm assuming you were looking for something similar to this. The problem is that mixing getline and cin leads to alot of issues. So I simplified it to just using getline so that your strings can hold spaces between words.
I included code that converts a string to a number for the age input.
The rest is up to you if you want to improve on this simple little program.
Hope that helped! :)
Thanks a lot.
However, I'm wondering if there is any other way to program this problem? Like only using basic codes with no while and if.
Or this is the only way to program the given problem above?

Thank again.
1. Use code tags please when you post code.
2. declare "address" as a type: std::string so you can use it with getline
3. after cin >> age; add cin.ignore() to ignore the "enter" press so cin can be used again
Topic archived. No new replies allowed.