Datatypes

Okay,for example if you have a program to just add two numbers that the user enters.
Would it be wise to have the datatypes as doubles? That way it can handle decimals and intergers? Or would that be considered bad programming in some way.

It would depend, really. You'd have to define a "number" somehow so the user knows what to input. As it stands, it's somewhat ambiguous.
That would be fine, I could just tell them to enter integers. But what if they don't? What if they enter a decimal? I still want my program to run successfully with the correct answer.
And to be honest I really don't want to define what the number should be.
That limits what the user can do. I want to have every possible case planned out. So if they enter a decimal, I can still do the calculation. Or even a ",".
Last edited on
If you want to error test, you could define them as doubles, then see if they entered a whole number using modulus, then convert their input into ints if you need the int.
Here is another way to do it, it removes the 20 characters after int is taken from the stream so the user can enter the next input. Not perfect, but works. Just need to make sure they hit enter, or space, you can change it to how you need.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main() {
    int a, b;

    std::cout << "Please enter two integers: ";
    std::cin >> a;
    std::cin.ignore(20,' '); // Ignore 20 characters until it reaches a space
    std::cin >> b;
    std::cin.ignore(20,'\n'); // Ignore 20 characters until it reaches a new line

    std::cout << "You entered " << a << " " << b;

    return 0;
}
@Volatile Pulse,
Yea, but the question, do I need to convert it to int?

Does it cause problems to just use double datatypes to do integer arithmetic? Or is bad programming?

Certain functions are defined using int, but using a double data type, you can simply cast it to int and be done with it. My thought, if you're going to have idiots try to break your code, one, cut their hands off, and two, spend several hours dummy proofing your code.
I see. I appreciate the replies.
However, I'm having trouble getting the modulus of a double.

Getting compiler error.
Invalid operands of types 'double' and 'int' to binary 'operator%'

This is what you were saying, yes?
num1 being a double.
1
2
if( (num1 % 1) != 0)
     // convert to int 
Last edited on
It doesn't matter whether console or gui. The user enters always strings. So why not take them as such?

You can easyly check for validity and convert later with stringstream:

http://www.cplusplus.com/reference/iostream/stringstream/
You could do:
int x = static_cast<int>(num1);

With the modulus, I was suggesting something similar, but I didn't know doubles couldn't be used. Learn something new everyday. And coder has a good idea, but the extra work isn't required for each program so most people don't both, give his idea some looking into.
Topic archived. No new replies allowed.