Yes, this is a homework assignment; not asking anyone to do it for me. The idea is to read in 10 digits, (1 or 0) and then calculate the decimal number. The code I have now works except that you have to put in exactly 10 digits (instead of "101", "0000000101").
I've been looking up cout.fill and stuff and I can't find out how to pad the variable with leading zeros. cout.fill only pads it for the output and doesn't pad the variable. I was thinking about sprintf() but not sure how to do it. The object of the homework was to convert binary to decimal, which I did, but I asked the professor and he says that he won't put in leading zeros. Any ideas anyone?
Code:#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { char binary[10]; double total = 0; cout << "Enter a 10 digit series of zeros and ones: " << endl; cin >> binary; cout.fill('0'); cout << setw( 10 ) << binary << endl; cout << binary << endl; for (int i=0; i<10; i++) { if (binary[i] == '1') { total += pow((double)2, (double)(9-i)); } } cout << "\nThe number you entered was: " << total << endl; cin >> total; }