I wonder how does vector with 3 elements, for example:
you type 010110001111
in the code:
you have 3 positions automatically separate each well, ("010", "110", "001", "111") converts to decimal ("2", "4", "1", "7"), done for convert binary to decimal, just missing this, you get the idea? Please help me. Thank you!
Write a function that reads 3 characters consisting of '0' and '1' and returns the number that they represent in binary, or -1 on error:
1 2 3 4 5 6 7 8 9 10 11
int read3Bits()
{
int result = 0;
loop 3 times doing {
read one character
if it isn't '0' or '1' then return -1
convert ASCII character to number 0 or 1
result = 2*result + (number from previous step)
}
return result;
}
Once you have this function, the rest should be pretty easy.
#include <iostream>
#include <stdlib.h>
#include <string>
usingnamespace std;
int main()
{
while (true) //To loop all this crap
{
cout << "Enter a binary number where the digits are evenly divisible by 3." << endl;
string OriginalUserInput;
getline(cin,OriginalUserInput); //Place user input into string OriginalUserInput
cin.clear(); // needed for getline, if you don't understand this don't worry about it. Just do it like nike.
int SizeOfString = OriginalUserInput.size(); //Get size of original input
if (SizeOfString % 3 != 0) //If entered number's digits aren't evenly divisible by 3
{
cout << "Error: Input's number of digits must be evenly divisible by 3." << endl;
} else //If entered number's digits are evenly divible by 3
{
for (int i=0; i< (SizeOfString/3); i++) //For loop from 0 to digits divided by 3.
//Ex. if 001001 is entered, this loop will run through twice since 6 digits divided by 3 = 2.
{
string ThreeDigitNumberToConvert; //This string will hold the three digit binary number that we will convert
ThreeDigitNumberToConvert = OriginalUserInput.substr(3*i,3*(i+1)); //Copies 3 of the digits to the string from our input
int ConvertedBinaryNumber = strtol(ThreeDigitNumberToConvert.c_str(),NULL,2); //Converts string to binary (Base 2)
cout << "Conversion: " << ThreeDigitNumberToConvert << " = " << ConvertedBinaryNumber << endl; //Display
}
}
}
return 0; //End of Program
}