#include<iostream>
#include<string>
usingnamespace std;
int bin2dec(const string binarystring); // Declaration of bin2dec prototype with one string parameter
int main()
{
cout << "Enter Q to terminate program.\n";
while(true)
{
string binary;
cout << "Enter a binary number: "; //prompt user to enter binary string
cin >> binary;
if (binary == "Q")
{
break;
}
cout << "The decimal equivalent of: " << binary << " is: " << bin2dec(binary) << endl;
// output of the binary string and its decimal equivalent
}
}
int bin2dec(const string binarystring) // Function definition with one string parameter
{
unsignedint result = 0 ; // creating int result to return to main function
for( char c : binarystring ) // for each character in the binary string
{
result *= 2 ; // shift result left by one binary digit
if( c == '1' ) result += 1 ; // add one if the bit is set
}
return result ; // Returning result to main function
}
Right now the code is in the form of a 'const string binarystring' and were supposed to be able to use 'const char binarystring[]' and for some reason whenever i try to switch it i run into problems when referencing the main function to the int bin2dec(...) function.
I wanted to know if theres a simple way to switch the prototype to an array type of function with [] without changing the entire code. Thanks!
Even left JLBorges comments :P
As far as the assignment it seems as if they want you to read in a bunch of strings to an array then pass that to the convert.
Maybe they want something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
std::size_t binaries;
std::cout << "Please enter the number of binary numbers: ";
std::cin >> binaries;
std::cin.ignore(1024, '\n'); //remove new line buffer
//so that way if the user enters their binaries like:
//0101 0000
//instead of
//01010000
//it will work
std::string *binaryNumbers = new std::string[binaries];
for(int i = 0; i < binaries; ++i)
{
std::cout << "Please enter binary number " << i+1 << ": ";
std::getline(std::cin, binaryNumbers[i]);
}
bin2dec(binaryNumbers);
Or maybe they want an array of characters instead of std::string?
I'm pretty sure your original program is correct. Does the assignment really say int bin2dec(const string& binarystring[])? Otherwise, the array version makes little sense... Although...