Having trouble fixing "string subscript out of range"

I am getting a "string subscript out of range" message when running this, but do not know what is wrong with my variable "inputchar" (it is used as an index).

(I just posted functions)

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

string isthisright;
int inputchar = 0;


string Sisthisright(string text, string targetword) {

	while (isthisright.length() != targetword.length()) {

		isthisright += text[inputchar];
		inputchar++;
		

	}
	inputchar -= targetword.length();
	return isthisright;
}

int occurances(string text, string targetword) {
	int numberofoccurances = 0;
	for (bool endoftext = false; endoftext == false; inputchar++) {

		if (targetword == Sisthisright(text, targetword)) {
			numberofoccurances++;
			text.erase(0, inputchar);
			inputchar = 0;
		}
		if (text[inputchar + targetword.length()] == '\0') {
			return numberofoccurances;
			endoftext = true;
		}
		else {
			isthisright.clear();
			continue;


		}

	}
	return numberofoccurances;
}
I am getting a "string subscript out of range" message when running this,

Where are you getting this error? Your debugger should be able to tell you exactly where it detected the problem and let you view the values of the various variables at the time of the crash.

but do not know what is wrong with my variable "inputchar"

Other that it being a global variable what makes you think there is something wrong with this variable?

The "string subscript out of range" message is an "Assertion Failed dialog box", not an error message that I would get in a list. For this reason, the message does not tell me the line that is causing the problem.
Last edited on
I think that their is something wrong with inputchar because (if I am right) "subscript out of range" means you are indexing an array (or in this case a string), with a bad index.
1
2
for (bool endoftext = false; endoftext == false; inputchar++) {
                                                 ^


Looks a little out of place.
It is necessary. To assign a value to isthisright, a segment of text is taken starting at inputchar. It must increase by one each time.
It is necessary. To assign a value to isthisright, a segment of text is taken starting at inputchar. It must increase by one each time.


That might be an acceptable answer if that was the only place inputchar was increased, but it is not.
Yes, in the while loop in Sisthisright I add to Inputchar, but once the loop ends, I subtract its value.
Can someone please just find the source of my problem?
If targetword is larger than text, you will have the problem you indicated. In that case, the index calculated on line 28 will be greater than the length of text.
I have tried messing with line 28, and am still getting the "Assertion Failed" dialogue box. This makes sense, though. The character '\0' represents the final character in a string.
Can someone please just find the source of my problem?

You'll need to post the smallest possible complete program that illustrates the problem if you want someone to locate the actual problem. But you should run the program with your debugger, your debugger will tell you the exact line where it detects the problem.


Last edited on
I use Visual Studio 2017, and do not get any "real" error message, but get the dialog box.

#include <iostream>
#include <string>
using namespace std;

string isthisright;
int inputchar = 0;


string Sisthisright(string text, string targetword) {

while (isthisright.length() != targetword.length()) {

isthisright += text[inputchar];
inputchar++;


}
inputchar -= targetword.length();
return isthisright;
}

int occurances(string text, string targetword) {
int numberofoccurances = 0;
for (bool endoftext = false; endoftext == false; inputchar++) {

if (targetword == Sisthisright(text, targetword)) {
numberofoccurances++;
text.erase(0, inputchar);
inputchar = 0;
}
if (text[inputchar + targetword.length()] == '\0') {
return numberofoccurances;
endoftext = true;
}
else {
isthisright.clear();
continue;


}

}
return numberofoccurances;
}

int main() {
string targetword;
string sentence;
cout << "targetword";
cin >> targetword;
cout << "text";
cin >> sentence;
cout << occurances(targetword, sentence);
return 0;
}
You are feeding the arguments to occurrances backwards. And since I would imagine the sentence is larger than the targetword, you're going to have the problem I mentioned earlier.

I use Visual Studio 2017, and do not get any "real" error message, but get the dialog box.

VS has a very high quality debugger. You would be doing yourself a favor by getting familiar with it.
https://docs.microsoft.com/en-us/visualstudio/debugger/index
What input leads to a crash ?
Your code looks awfully complicated. What is it supposed to do ?
Last edited on
My code counts the amount of times a word is found in a string. I have another function that you can replace occurances with, but it stops at the fist time the targetword is found.
here it is:

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
string look_for_keyword(string text, string targetword, string replace = "no") {

	int replacechar = 1;
	for (bool wordfound = false; wordfound == false; inputchar++) {

		if (targetword == Sisthisright(text, targetword)) {

			if (replace != "no") {
				while (targetword.length() - replacechar != -1) {

					text[inputchar + 1] = replace[targetword.length() - replacechar];
					inputchar--;
					replacechar++;
				}
				return text;
				wordfound = true;

			}
			else {
				return "found" + to_string(inputchar);
				wordfound = true;
			}

		}
		if (text[inputchar + targetword.length()] == '\0') {
			return "Not Found";
			wordfound = true;
		}
		else {

			
			isthisright.clear();
			continue;


		}

	}
	
	return "test";

}
Last edited on
It is very similar to the function that is giving me the error.
An easier way to count and replace words in a string.
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
#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstdio>

using namespace std;


// replaces old_val with new_val in input and returns 
// number of replacements -  output is stored in output
// assumes that old_value doesn't contain spaces
int replace_word(const string& input, string& output, 
        const string& old_val, const string& new_val)
{
  istringstream iss(input);
  string tmp;
  int count = 0;

  if (input.empty() || old_val.empty()) 
    return 0;

  while (iss >> tmp)
  {
    if (tmp == old_val)
    {
      count++;
      output += new_val + " ";
    }
    else
    {
      output += tmp + " ";
    }
  }
  if (output.back() == ' ') // remove trailing ' '
    output.resize(output.size()-1);

  return count;
}
// returns the number of occurences of needle in the haystack
int count_word(const string& haystack, const string& needle)
{
  int count = 0;

  auto pos = haystack.find(needle, 0);
  while (pos != string::npos) // as long as we find a needle
  {
    count++;
    pos = haystack.find(needle, pos + 1); // continue searching
  }

  return count;
}

int main()
{
  const string input = "Anna Lisa Debbie Anna Chrissie Kathy Anna";
  string output;

  int num_replacements = replace_word(input, output, "Anna", "Swetlana");
  cout << "Testing replace function\n";
  cout << "Replacements: " << num_replacements << "\n";
  cout << "Output: " << output << "\n";

  cout << "Testing count...";
  int count = count_word(input, "Anna");
  cout << "Count of Anna: " << count << "\n\n";

  system("pause");
}
Topic archived. No new replies allowed.