I'm very new to computer science. My teacher gave us an assignment to greet someone, ask for their age, and determine what year they were born in. For example: Hello Bob, you are 21 years old and you were born in 1999!
// This program will greet the user and ask for their name and age.
#include <iostream>
usingnamespace std;
int main()
{
int name, age, year_born;
// Ask for the user's name
cout << "Hello, what's you name? ";
cin >> name;
// Ask for the user's age
cout << "What is your age? ";
cin >> age;
// Now we must calculate the user's age (assume their birthday is on January 1st)
// The current year is 2020
int year_now = 2020;
// Now we subtract the user's age from the current year, which is 2020
year_born = 2020 - age;
// Display the user's name, age, and the year they were born
cout << "hello " << name;
cout << "you are " << age;
cout << "you were born in " << year_born << endl;
}
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
I found the second link to be the most help.
Your first problem is that you are trying to store a string in an "int", This does not work and will cause "cin" to fail and be unusable the rest of the program.
You need to include the header file <string> and use a std::string for "name". Also "std::getline()" would be a better choice than formatted input (cin >> name).
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
int age, year_born;
std::string name;
// Ask for the user's name
cout << "Hello, what's you name? ";
std::getline(std::cin, name);
After that the program look OK, but I will give it a test to see what happens.
// This program will greet the user and ask for their name and age.
#include <iostream>
usingnamespace std;
int main()
{
// The current year is 2020
constexprint YEAR_NOW = 2020; // <--- Changed. And moved. Or you could use "const".
int age, year_born;
// Great the user.
cout << "Hello...\n"; // <--- This needs changed to a greeting.
// Ask for the user's age
cout << "\nWhat is your age? ";
cin >> age;
// Now we must calculate the user's age (assume their birthday is on January 1st)
// Now we subtract the user's age from the current year, which is 2020
year_born = YEAR_NOW - age;
// Display the user's name, age, and the year they were born
cout << "\nYou are " << age;
cout << " and you were born in " << year_born << endl;
return 0; // <--- Not required, but makes a good break point.
}