Ranged for loop problem

I recently upgraded to VS 2012 to experience some of the new features in C++11 like ranged for loops. However I seem to be running into a problem and have no idea where I'm going wrong. Here's the code in question:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void encrypt(std::string to_encrypt, std::string file_name)
{
	char key_to_encrypt;
	std::filebuf fb;
	fb.open(file_name, std::ios::out);
	std::ostream file(&fb);

	std::cout << "\nEnter character to use for encryption: ";
	std::cin >> key_to_encrypt;

	for (char& temp : to_encrypt)
	{
		to_encrypt[temp] ^= key_to_encrypt;
		file << to_encrypt[temp];
	}

	file << key_to_encrypt << std::endl;

	fb.close();
}


At first I thought the problem may be coming from somewhere else but even with the code below I get the exact same problem.

1
2
3
4
5
6
std::string str = "hello world";

for (const char& i : str)
}
	std::cout << str[i];		
}


Error message is subscript out of range, file xstring, line 1662.
That's because i in that code does not assume the index across it's range.

It is a reference to the character itself.

Ditch str[], and keep the i, only probably call it c or something. Otherwise, you are indexing into the string with ascii values, hence the subscript out of range error message.
Last edited on
Topic archived. No new replies allowed.