Reputation: 23
the purpose of this code is to replace words that have 1 character with "|", words with 2 characters with "||", and words with 3 characters with "---". Every time I run it it gives me an error:
string subscript out of range
Any idea what could be causing it?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
int x, i, count=0;
cout << "Enter the string of text you wish to modify" << endl << "(Make sure to inlude a period at the end of the text)" << endl;
getline(cin, text);
x = text.length();
cout << x;
if (text[x - 1] == '.')
{
for (i = 0; i <= x; i++)
{
count++;
if (text[i] == ' ')
{
if (count == 1)
{
text[i - 1] = '|';
count = 0;
}
else if (count == 2)
{
text[i - 2] = '|';
text[i - 1] = '|';
count = 0;
}
else if (count == 3)
{
text[i - 3] = '-';
text[i - 2] = '-';
text[i - 1] = '-';
count = 0;
}
else if (count > 4)
{
count = 0;
}
}
if (text[i] = '.')
{
if (count == 1)
{
text[i - 1] = '|';
}
else if (count == 2)
{
text[i - 2] = '|';
text[i - 1] = '|';
}
else if (count == 3)
{
text[i - 3] = '-';
text[i - 2] = '-';
text[i - 1] = '-';
}
}
}
cout << "Here is your modified sentence" << endl << text;
}
else
{
cout << "Your statement does not end in a period, goodbye" << endl;
}
return 0;
}
Upvotes: 2
Views: 57
Reputation: 2329
"subscript out of range" means you are indexing an array with a bad index.
try
for(i=0;i<x;i++)
or you can use a switch statement with text.length().
http://www.cprogramming.com/tutorial/lesson5.html
Upvotes: 3