此代码的目的是将具有 1 个字符的单词替换为“|”,将具有 2 个字符的单词替换为“||”,将具有 3 个字符的单词替换为“---”。 每次我运行它时都会出现错误:
string subscript out of range
知道是什么原因造成的吗?
#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;
}
最佳答案
“下标超出范围”意味着您正在使用错误索引对数组进行索引。
尝试
for(i=0;i<x;i++)
或者您可以使用带有 text.length() 的 switch 语句。
关于c++ - 用不同字符替换单词的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890040/