I am very new to c and I was trying to put together a script that just says how much older/younger someone is than me. The problem is the std::cin isn't working, it's not letting me say the input age. How do I make this work?
#include <iostream>
int main()
{
int age;
int diff = age - 20;
std::cout << "What is your age?\n";
std::cin >> age;
/* There should be an option to say the age, but it goes right into the next code with a random number */
if (diff < 20) {
std::cout << "You are " << diff << " years younger than me.\n";
}
else if (diff > 20) {
std::cout << "You are " << diff << " years older than me.\n";
}
else if (diff = 20) {
std::cout << "You are my age.\n";
}
}
CodePudding user response:
When you say int age;
, there's no rhyme or reason to the bits stored in memory that represent that integer. It's undefined behavior, but it will be equal to some random value based on what bits happen to be there. You then use std::cin
to store an integer there, which works fine (assuming your code keeps chugging along despite using age
before it has a value). Your conditionals then compare diff
, which has a random value minus 20
, with 20
, outputting the right statement based on whatever was stored in diff
. For example, when I ran your code, I got the output, "You are -1635346580 years younger than me." To fix this problem, read the value of the user's age before using it like this:
int age;
std::cout << "What is your age?\n";
std::cin >> age;
int diff = age - 20;
Additionally, when you wrote else if (diff = 20)
, you used an assignment operator. That puts the value of 20
into the variable diff
. It then returns that value for use in the expected Boolean. In C , 0
translates to false
, and everything else translates to true
. That means, once it gets there, it will always execute since 20
becomes true
. Your program will always function correctly, however, since by that point in the code, diff
is guaranteed to be 20
since it's neither greater than 20
nor less than 20
. You could say else if (diff == 20)
to do the comparison, but I'd replace it with else // diff is 20
since you know the value by that point.
CodePudding user response:
You might need to refactor this with the getline()
function from the standard library. You will, however, need to convert the standard string
to a integral data type.
std::string ret;
std::cout << "What is your age?" << std::endl;
std::getline(std::cin, ret);
int age = std::stoi(ret); // generally, this should be a good enough conversion. however remember: user input is always evil.
Also, try to refrain from using line breaks manually in a string literal and use the standard library's endl