binary to dec...

Im writing a programmm witch should covert bin to dec...so far i've got this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main(){
   string bin;
   int i,a;
   float dec,b=1;
   cout << "Give binary code: ";
   cin >> bin;
   dec=0;
   i=bin.size();
   for( i=i ; i>=0; i-- , b=b*2){
		if (bin[1] == '1') a=1; 
		else a=0;
        dec=dec+a*b ;                
   }
   cout << dec;
   system("pause");
   return 0;
}


I dont know...I thing it should work...could some tell me what is wrong?
i=bin.size() - 1; if (bin[i] == '1') a=1; // note: i not 1
you're code is certainly a subject to improve
Last edited on
Also, it would be a good idea to put iinside the parenthesis, like this:

for(int i=bin.size()-1;i>=0;i--,b*=2)

If you leave it outside then bad things can happen as your code gets more complicated.

Also notice that you can use combined assignment operators in C++.
1
2
b*=2;//This is the same as b=b*2
dec+=a*b;//This is the same as dec=dec+a*b 

This will make your code look a bit cleaner.
i dont understan, why should i change
i=bin.size();
to
i=bin.size() - 1;
if i do that my programm will skip last digit of my string.

and i cant change 1 to i becouse i is number of char in my string.

could you explain?
The first location in a string is indexed as a zero.
bin[0];//This is the first location.
That means if bin contains 5 characters (for example), it will go from bin[0] to bin[4]

You have to take one off of the size or it will go too far and go past the end of the string.
ok i understan now. but what about changing 1 to "i" ?

And my programm still doesn't work...so something is still wrong. And It wont get comlicated its basicly the end...i just need it for my classes...

edit: sory my bad. i know what did you mean with "i" Thanks
Last edited on
Topic archived. No new replies allowed.