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;
- 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.
#include <iostream>
#include <string>
#include <sstream>
usingnamespace 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?
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