Is it possible for an int (or any integer type) to have multiple sign characters?

Let's say for example you have a program that asks the user to enter a negative number, then the program will store that negative number in a int variable. Is it possible for that int variable to hold multiple "-" characters?

by the way, how can i check if a number has multiple leading sign characters?

 
int negativeNumber = --5   //is this possible? 
Yes it is possible. They will collapse per math rules: --5 == +5

Why do you even need several sign characters.
Last edited on
As an integer, no.

In memory, an integer has one sign bit, which can be set to 1 (it's a negative number) or 0 (it's a positive number). So --5 will be converted to a positive 5 before being stored into negativeNumber.

If you must store both negative signs, one potential thing you could do is store it as a string. You would have to convert it before using it as an integer to add/subtract though.
I was just experiment whether or not a non-string type variable can hold multiple sign characters. But clearly an int can't hold more than one.

Is there any other type that can hold multiple sign characters? (and i don't mean strings)
Why do you need them? There is no such things as multiple signs in math, so it is logical that arithmetic types that mirrors common math cannot do it either.

You can always define your own class with integer-like semantic which can hold multiple signs, but why would you do that?
To my knowledge, no. As MiiNiPaa said, you could create your own, but we'll have to know more about your requirements to help you.
Hmm, i think it might be better if i re-phrase the question in a different way..

If i made a program that asks a user to input a negative number, and the user inputs --5, how can I validate the input?

Is it possible to somehow remove the extra sign character from the integer variable? since it seems that cin will end the program prematurely if i input --5.

P.S its not that i need them, i am just finding ways to validate input for integers
Depends on how you are getting your input. Consider the following example:

1
2
3
cout << "Enter in integer";
int a;
cin >> a;


In that example, I could input "ABCDEFG". That's invalid input, and that's not as simple to convert to an integer as removing a sign. There are several wrong inputs I could put in there.

In addition, you could input ---5 (with three minus signs) - should you still accept that?

If you only need to validate the input (and you don't need to save --5 as 5), using cin.good() (that returns a boolean) will tell you if the input was valid.

If you still need to save --5 as 5, then you need to be specific in which invalid inputs you need to still be able to use as an integer.
Last edited on
cin.good()
You can also just check the state of the stream like
1
2
if(!cin)
    //clean up and try again 
Topic archived. No new replies allowed.