"String subscript out of range."

Hello all,

I am working on an assignment for my intro to programming class. The program is supposed to read input from a file, encrypt it, then write the encrypted data to a new file. The code is still a work in progress, but I've reached a major roadblock.

I'm using a for loop to encrypt each character in a line individually. Every time I try to run the program, I get a fatal error in this for loop, saying that the string subscript is out of range. I have been working on this error for the better part of two hours, and cannot see anything different about this loop than any other for loop I've written in the past.

Any ideas what the issue here may be?

Thanks in advance!

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
  #include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
	ifstream inputFile("plain.txt", ios::in);
	ofstream outputFile("coded.txt", ios::out);

	string inLine;
	string outLine;
	int line = 1;
	int encrypt = (line - 1) % 5 + 1;

	if (inputFile)
	{
		getline(inputFile, inLine);

		while (inputFile)
		{

			for (int index = 0; index < inLine.size(); index++)
			{
				outLine[index] += (inLine[index] + encrypt);
				outputFile << outLine << endl;
			}

			line++;

			getline(inputFile, inLine);

		}

	}
	else
		cout << "Error opening file..." << endl;

	return 0;
What do you think the length of outline is on line 24?
try just outline += without the index (concat a letter or a substring to outline)
That worked! The output is not at all what I wanted, but it got rid of the error!

Thank you!
Perhaps this is nearer to giving the required output?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	std::ifstream inputFile("plain.txt");
	std::ofstream outputFile("coded.txt");

	if (!inputFile || !outputFile)
		return (std::cout << "Cannot open files\n"), 1;

	size_t line {};

	for (std::string inLine; std::getline(inputFile, inLine); ++line) {
		std::string outLine;
		const auto encrypt {line % 5 + 1};

		for (const auto& ch : inLine)
			outLine += static_cast<char>(ch + encrypt);

		outputFile << outLine << '\n';
	}
}

Last edited on
As I see, It may have something wrong with for (int index = 0; index < inLine.size(); index++).

the type of index is int, which is signed, whereas the type of inLine.size() is string::size_type which is unsigned. the result of "index < inLine.size()" may be unexpected.

Maybe you could try to use for (decltype(inLine.size()) index = 0; index < inLine.size(); index++).
The return type of .size() is size_t. So simply:

 
for (size_t index {}; index < inLine.size(); ++index)

Topic archived. No new replies allowed.