此代码的目的是将带有1个字符的单词替换为" |",将带有2个字符的单词替换为" ||",将带有3个字符的单词替换为& #34; ---&#34 ;. 每次我运行它都会给我一个错误:
字符串下标超出范围
知道可能导致它的原因吗?
#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;
}
答案 0 :(得分:3)
“下标超出范围”意味着您正在索引具有错误索引的数组。
试
for(i=0;i<x;i++)
或者你可以使用带有text.length()的switch语句。