Help with a binary to decimal converter

Hello, I am doing a problem where I have to convert a random binary input via a string to a integer that is in decimal. I cant seem to figure out how to enter the equation into my function. Which is (((a[0]*2)+a[1])*2+a[2])*2+a[3]... . Currently I am trying to use a loop which goes through every 1 and 0 in the string and converts it into an integer. But after that I just cant think of how to get it to proceed any further along by plugging it into the function.I have tried doing a few things in the loop but none of them have worked so far. Can anyone help or give a hint as to how to let it convert every number in the string to an integer then allow me to input each one into a function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <string>
using namespace std;

string a;

int input();

int main()
{
	input();

	int decimal, x, length, total = 0;
	length = a.length();
	
	for (x = 0; x < length; x++)
	{
		int num = a[x] - '0';
		num = num * 2;
		
	}
	
	cout << endl << total;
	a[1] * 2;
	cout << endl << a;

	int stop;
	cin >> stop;
	return 0;
}

int input()
{
	int x, x2, count, repeat = 0;
	
	while (repeat == 0)
	{
		cout << "Enter a string representing a binary number => ";
		cin >> a;
		count = a.length();
		for (x = 0; x < count; x++)
		{

			if (a[x] != '0' && a[x] != '1')
			{
				cout << a << "is not a string representing a binary number" << endl;
				repeat = 0;
				break;

			}
			else
				repeat = 1;
			
			

		}

	}
	return 0;
}
Change your for loop:
1
2
3
4
5
6
7
8
	for (x = 0; x < length; x++)
	{
		total = total * 2;
		total += a[x] - '0';
		
	}
	
	cout << endl << total;

Topic archived. No new replies allowed.