Issue
I am doing some simple decimal to binary conversion using a while loop, and I realized that my output from the loop needs to be reversed, which i did so by creating a stringstream and then moving my generated int into a stringstream which then converts it to a string and then reverses the order for the string to get the correct binary value... but when I actually run the code, there's like a random 1 or 0 out in front of everything...
#include <iostream>
#include <sstream>
#include <algorithm>
int main() {
std::stringstream ss;
int decimal;
int binary;
std::cout<< "\n Please enter decimal value: ";
std::cin >> decimal;
std::cout << "\n The binary equivalent of " << decimal << " is ";
while(decimal > 0 ) {
binary = decimal % 2;
decimal/= 2;
std::cout << binary;
}
ss << binary;
std::string binary_string = ss.str();
std::reverse(binary_string.begin(), binary_string.end());
std::cout << binary_string;
}
For example, if I input an 11 I get this:
Please enter decimal value: 11
The binary equivalent of 11 is 11011
For 12:
Please enter decimal value: 12
The binary equivalent of 12 is 00111
Solution
The extra bit is coming from
ss << binary;
string binary_string = ss.str();
reverse(binary_string.begin(), binary_string.end());
cout << binary_string;
after the loop. binary
is either going to contain a 1
or a 0
and converting that to string and reversing it is going to give you the same thing. You need to move ss << binary;
into the loop so it contains all the binary digits you generate.
Answered By - NathanOliver Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.