Hi, I’m new to C++ and I created a program that calculates my dogs age. However, when I change the value of dog_age the answer is still 25 years old. Why?
#include <iostream>
int main() {
int dog_age = 10;
//age of my dog
int early_years = 21;
//first two years of my dogs' life
int later_years = (dog_age - 2) * 4;
//for my dogs' following years
int human_years = early_years + later_years;
//for my dogs' total human years
std::cout << "My name is Oreo! Ruff ruff, I am " << human_years << " years old in human years. \n";
//output statement that gives user their dogs calculated age in human years
the URL is https://www.codecademy.com/courses/learn-c-plus-plus/projects/cpp-dog-years
}
You may need to compile each time you change the code.
So you might need to do
g++ dog_years.cpp
after saving every time,
otherwise what’s in the a.out
file may not change.
./a.out
just runs what’s in that file.
3 Likes
In order to avoid having to recompile the program for each new input, I pass in arguments from the command line (or terminal).
- get input from command line arguments (
argv
)
- convert
const char*
to int
using std::stoi()
#include <iostream>
void dogYearsToHuman(int dogAge) {
int earlyYears, laterYears, humanYears;
earlyYears = 21;
//first two years of my dogs' life
laterYears = (dogAge - 2) * 4;
//for my dogs' following years
humanYears = earlyYears + laterYears;
//for my dogs' total human years
std::cout << "My name is Oreo! Ruff ruff, I am " << humanYears << " years old in human years. \n";
//output statement that gives user their dogs calculated age in human years
}
int main(int argc, char const *argv[])
{
// get input from command line arguments (argv)
const char* n = argv[1];
// convert const char* to int using std::stoi()
int x = std::stoi(n);
dogYearsToHuman(x);
return 0;
}
➜ ~ ./a.out 14
My name is Oreo! Ruff ruff, I am 69 years old in human years.
➜ ~ ./a.out 5
My name is Oreo! Ruff ruff, I am 33 years old in human years.
➜ ~ ./a.out 2
My name is Oreo! Ruff ruff, I am 21 years old in human years.
➜ ~
1 Like