Can't find why my 'for loop' is out of range

The code I'm focusing on is the code between the '//Start' and '//End' comments.

I am creating a program, and I'm not seeing how the for loop could go out of range.

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
#include <iostream> 
#include <string>
using namespace std;

int main()
{
	string x;
	cout << ": ";
	cin >> x;
	int lgth=x.length();
	int * myarray = new int[lgth];

	//Start
	for (int y=0; y<(lgth-1); y++){
		myarray[y]=((x.at(y)));
	}
	//End
	
	for (int z=0; lgth; z++){ 
                cin.get()
		cout << myarray[z] << " ";
	}
	cin.ignore();
	cin.get();
	return 0;
}



FYI, 'lgth' is the length of the users input. ex: "ab12" has a length of 4. I subtract 1 from 'lgth' because arrays start at 0. If you keep pressing enter you'll see it spits out a bunch of random numbers and then crashes... The mark it's going out of range. I've tested many different symbols in the for loop in conjunction with taking the '-1' away from 'lgth'. Anyone who could shed some light on this problem would be greatly appreciated.

P.S.

If you're wondering what this program does. It takes the users input and creates an array out of it, and then it prints it out (it's going to be a segment in my cipher).
closed account (zb0S216C)
It seems that on line 14, you are not giving the loop access to all of the characters in the string.
On line 19, in the for loop, you have an incomplete condition. You don't specify when the for loop should stop.
Next time, could you please try the code before guessing what's wrong. I've surrounded the aforementioned 'for loop' with cin.get(), and that's the one giving the error. With the above for loop, I've tried all the different symbols, <, >, !=, even = (which, obviously, doesn't work). Changed line 19 though has made it not crash, but it still spits out 4 random numbers.

EDIT: Framework, while your answer was only half complete, it got me to fix it. I used the '<' symbol while taking away the '-1' from 'lgth'. I also completed the second for loop, but I still have an issue. Instead of printing out what you put in. It prints out random numbers which are ascii codes if I'm correct (a is 97, b is 98, 1 is 49, 2 is 50 etc. etc.). Anyone know how to fix this in C++? I new how to convert this in Python :/.

EDIT: Fixed it. Somehow it was converting the items on line 21 to ascii codes. So it's working now.

Last edited on
Topic archived. No new replies allowed.