Help with Dog_Years Lesson in the Learn C++ syllabus?

Hiya!

I’m working on the “Dog_Years” lesson in “Learn C++” but I’d like for the user to be able to write their dog’s name and their dog’s age.

I’ve set the code up for the user to be able to put both the name and the age in by using cin. However, when I run the code, the program only allows the user to input during the first cin and completely skips the second, which makes the dog’s age some ridiculous number. Any ideas on how to fix this?

Or is std::cin>> only a one time input kind of thing?

Code below:
#include
int main() {
int dog_name;
int dog_age;
int early_years = 21;
int later_years = 0;
int human_years = 0;

//Let user write Dog’s name & age.
std::cout << “Please write your dog’s name here. \n”;
std::cin >> dog_name;

std::cout << “Please write your dog’s age here. \n”;
std::cin >> dog_age;

//Calculate

later_years = (dog_age-2)*4;
human_years = (later_years + early_years);

//Output

std::cout<< dog_name << " is " << human_years << " years old!\n";
return 0;

Any help would be greatly appreciated!

Thanks Tim!

Hi future readers who might stumble on this,

The reason the code doesn’t work above is because a dog’s name is a string, not an interger. This means I needed to #include “string” library and can be initialised with “std::string dog_name;”

  • note the libraries are in this text are using “”'s instead of the pointy brackets because the point brackets hide things in this forum, but for you code please use <

Here’s the working code:

#include “iostream”
#include “string”

int main() {
//Step 0 - Initialising variables
std::string dog_name;
int dog_age;
int early_years = 21;
int later_years = 0;
int human_years = 0;

//Step 1 - Let user write Dog’s name & age.

std::cout << “Please write your dog’s name here. \n”;
std::cin >> dog_name;

std::cout << “Please write your dog’s age here. \n”;
std::cin >> dog_age;

//Step 2 - Calculate the dog’s age

later_years = (dog_age-2)*4;
human_years = (later_years + early_years);

//Step 3 - Output

std::cout<< dog_name << " is " << human_years << " years old!\n";
return 0;

}

1 Like