I am writing this program which will allow you to calculate kinetic energy via it's formula. But I have stumbled across a problem.
I use double variables to get an input from the user. This variable get's assigned by the user with any number to their choice OR a question mark (?). BUT when I use that double variable in an IF statement to check if they inputted a number or a ? I get an error. I don't have a clue on how to solve this. Can someone please help me out?
I get the error at the IF statements at the bottom of the code.
The error says:
error: invalid operands of types 'double' and 'const char [2]' to binary 'operator=='|
Haha you are right there, but if I use these as a string instead of a double I cannot hook up a sum to them. Because then it is going to say that std::string can't be converted to double...
I think I see what you're trying to do here. For each value, you can accept it as a string and then try to convert it to a double - if that conversion fails, you know it as probably not a real number:
1 2 3 4 5 6 7 8 9 10 11
std::string value_str;
std::cin >> value_str;
double value = 0.0;
if(std::istringstream(value_str) >> value)
{
//it was a real number
}
else
{
//it was not a real number
}
I recommend some sort of utility function to reduce code duplication.
Referring to LB's post, replace line 6 with whatever you want to do with the value. Line 4 has successfully put the double value in the variable called value. The fact that you're at line 6 indicates the conversion of the input to a double was successful. You might not need to do anything at all.
Line 10 is where you want to test if is value_str == "?". Line 4 has failed to convert the input to a double. You of course have the situation that you have to deal with where the input is a string, but is not "?".