i dun understand.. what's happenin in my code?? :((

ok, here's the code:
---------------------------------------------------
#include <iostream>
#include <string.h>
#include <conio.h>

using namespace std;

int bd (char bin[]){

int c,x=0,i,factor=1;
int decimal=0;
//char bin[20];
int len;

do{ //this is for my input, binary input.
bin[x]=getch();
if ((bin[x]>='0') && (bin[x]<='1')){
cout<<bin[x];
x++;
}
else if (bin[x]==13){
bin[x]='\0';
}
}while (bin[x]!='\0');

len = strlen (bin)-1;

for (i=0;i<=len;len--){ //and this is for the calculation
c = atoi (bin); //from binary to decimal
c = bin[len];
if (bin[len]==49){
c=bin[len]-48;}
else if (bin[len]==48){
c=bin[len]-48;}
decimal = decimal + c*factor;
factor = factor*2;
}
return decimal;
}

main (void)
{
int x,y,z;
char inp, ab[100];

x=bd (ab);
cout<<endl<<x;

system ("PAUSE");
return 0;
}
------------------------------------------------

The loop shouLd end when the user presses the "enter" button, but when I tried to run the code, it stops whenever it reaches up to 7 characters.. whyy??? ;(( whats wrong with my code? help pleasssE!! :((
Can you tell me what exactly are you trying to do ?
you can skip this else part
1
2
3
4
5
/*else if (bin[x]==13)
				{
					bin[x]='\0';
				}*/
		}while (bin[x]!='\0');


and modify while as
1
2
  }while (bin[x]!= 13);
                    bin[x]='\0';


also you are not doing proper char to decimal conversion over here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (i=0;i<=len;len--)
			{ //and this is for the calculation
				c = atoi (bin); //from binary to decimal
				c = bin[len];
				if (bin[len]==49)
					{
						c=bin[len]-48;
					}
					else if (bin[len]==48)
						{
							c=bin[len]-48;}
							decimal = decimal + c*factor;
							factor = factor*2;
						}
Firstly, it's int main().
I think your problem is because you compare bin[x] to '\0' after incrementing x. That means you're comparing the char after tho one you just entered.
I don't see why would you want to do this at all though. You could use the standard input functions here...
Also, lines
1
2
c = atoi (bin); //from binary to decimal 
c = bin[len];

You set c and then you set c again. The first line of these two has no effect at all

1
2
3
4
if (bin[len]==49){
c=bin[len]-48;}
else if (bin[len]==48){
c=bin[len]-48;}

These lines have problems too. They do the same thing but for some reason you feel you need branching here. There is an || operator for cases like that. Though I don't think you need that either. c = bin[len]-48; should be enough. (note that now the previous line 'c= bin[len]' is useless)

Lastly, don't use system("pause")
see http://www.cplusplus.com/forum/articles/11153/
`hey guys, thanks, i got the code w your help ! ! ^_^
Topic archived. No new replies allowed.