You can stream the integer to a stringstream, so you can parse individual digits and use the length of the string to determine what power of 2 to multiple by.
int bin(001110);
std::stringstream ss;
ss << bin; //Stores 001110 as individual digits in a buffer (no longer an integer)
//str() is a function that returns a std::string object
for(size_t I(0); I < ss.str().size(); ++I)
std::cout << ss.str()[I] << '\t'; //Because it is a string, you can use [] to access individual characters, or "digits"
I've heard of a new "to_string()" function from C++11 that let's you convert a number to a std::string directly.
cout << "Enter an integer " << endl;
int number;
cin >> number;
//convert the number into digits
//lets say the number is 12345, of course this would require 5 variables,
int n1,n2,n3,n4,n5;
n1 = number%10;
number /= 10;
n2 = number%10;
number /= 10;
n3 = number%10;
number /= 10;
n4 = number%10;
number /=10;
n5 = number%10;
number /= 10;
cout << n1 << endl;
cout << n2 << endl;
cout << n3 << endl;
cout << n4 << endl;
cout << n5 << endl;
#include <iostream>
int main()
{
std::string number;
std::cout << "Enter an integer " << std::endl;
std::getline( std::cin , number );
for( constauto &it : number ) std::cout << it /*-'0' if you want them to be ints and not chars*/ << std::endl;
}
I am new to programming as well so I have not yet seen anything like that. Thanks though! I have a hard time turning off the Uni way of doing everything from scratch.
Hi guys, I'm sorry about my late response. I have read all your replies here and I found erock 88 code very simple, but It's only print the rightmost digit so I add some string to see which n is the output. I get only rightmost digit without any string. here is the code
The program works fine. the difference between erock's code and mine is that his only works with numbers exactly 5 digits long and adjusting it for different sized numbers would be more cumbersome than needed. Mine is written to work with integers of any length, but does not split up the number into digits as it converts a binary number to integer directly. It can be adapted for converting to digits, however.
If you don't want the result to be displayed in reverse, then reverse the order you display the n# variables.