for loop crashes my program. Don't know why

So my program compiles and runs. In trying to fix a bug I caused my program to crash. Below is first the "buggy" code and below it is the code that crashes the program. The problem is in the middle condition for my first for loop. i<=x makes it bug (for reasons obvious with the code) and i<=z causes it too crash before couting output although it couts all the ints above. If it helps the program is supposed to convert a string of numbers in a specified base into a different specified base. This function is just my start. Also included class and constructor if that helps.
-Thanks

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class InVal
{

public:
int inputBase;
std::string value;
int counter;
int output;
InVal();
void PrintAsBase();

};

InVal::InVal()
{
inputBase=0;
counter=0;
output=0;
}




void InVal::PrintAsBase()
{
	int output=0;
	cout<<"enter the base and number"<<endl;
	cin>>inputBase;
	cin>>value;
	
	int x = value.length();
	//int z=value.length();
	cout<<"lenthg is "<<x<<endl;
	for(int i =0;i<=x;i++)
	{
		int y =value.at(i)-'0';
		cout<<y<<endl;
		
		for(int j=x;j>=0;j--)
		{
			output+=y*pow(inputBase, j-1);
			break;
		}
		x--;

		counter++;
	}
			cout<<output<<endl;
	
}


/////////////////////////////////////////////////////////////



void InVal::PrintAsBase()
{
	int output=0;
	cout<<"enter the base and number"<<endl;
	cin>>inputBase;
	cin>>value;
	
	int x = value.length();
	int z=value.length();
	cout<<"lenthg is "<<z<<endl;
	for(int i =0;i<=z;i++)
	{
		int y =value.at(i)-'0';
		cout<<y<<endl;
		
		for(int j=x;j>=0;j--)
		{
			output+=y*pow(inputBase, j-1);
			break;
		}
		x--;

		counter++;
	}
			cout<<output<<endl;
	
}



Check that your not running past the last index of your array. Remember arrays start at 0. I noticed your For..Loop using <= so assuming you had a length of 10, it would be doing 0-10 which is 11.

You should be doing for(int i = 0; i < 10; i++) which would loop 0 - 9

Topic archived. No new replies allowed.