C program stops reading input after getting a negative number as input

Back to Programming Languages forum

Shreyansh Chouhan     2019-05-26 12:47:11

Stuck on problem #81. Language: C++. Input using: cin. Data type: int32_t (for 32 bit integers) Can't take input for negative numbers, the program only outputs the correct number of bits upto the point the number it encounters are all positive, there is no output for and after the first negative input. Please help :(

kittyaurel     2019-05-26 13:40:31
User avatar

Hi. I recently came across that problem. I solved it by casting the input numbers to unsigned integers. I don't exactly know why it worked though ^^' Edit: I've read it again. It could be the initial size of your read buffer. Firstly, get the input with fgets, then use strtok to slize it into tokens and turn them to integers with sscanf.

Rodion (admin)     2019-05-26 13:47:14
User avatar

Hi Friend!

One funny thing you may note that in many languages "shift right" operator comes in two forms - arithmetic and logical. They differ in how the highest bit is filled after shift. Try this example

int32_t a = -1;
a >>= 1;
cout << a;
a >>= 1;
a >>= 1;
a >>= 1;
cout << a;

Unpleasant thing is that C++ (probably) lacks "logic" shift so you may need nullify highest bit manually after shift.

Other approach as kittyaurel suggests is to treat value as unsigned (if the language allows it).

The whole idea of this problem, anyway, is to make us acquainted with machine binary representation and bit operations, which may be queer in some languages. So don't get frustrated :)

Hope this helps!

Shreyansh Chouhan     2019-05-27 07:29:11

Thanks a lot @kittyaurel and @Rodion! I will try and keep the input in unsigned variables and see if that works! Also didn't know about the second type of shift right operator, should read up on that ^_^ Thanks once again!

EDIT: Declaring the input as an unsigned int works!

Please login and solve 5 problems to be able to post at forum