gpt4 book ai didi

c++ - 用不同字符替换单词的代码

转载 作者:搜寻专家 更新时间:2023-10-31 01:41:02 25 4
gpt4 key购买 nike

此代码的目的是将具有 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 语句。

http://www.cprogramming.com/tutorial/lesson5.html

关于c++ - 用不同字符替换单词的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com