我正在"string subscript out of range error".我不知道为什么



我搜索了网站,但找不到解决问题的方法。我试着做了一些小的修改,但什么都没解决。我一直得到"字符串下标超出范围"的错误。我不知道为什么。也许我是盲人,我在某个地方错过了一个小错误。现在我在这里请求援助。

程序信息:该程序将输入名字和姓氏,验证并应用大小写转换。用户输入姓名后,它将清除屏幕并显示用户输入的姓名。然后,它将输入产品评级,对其进行验证,并应用案例转换。显示与5个产品值相对应的标题和条形图。

编辑:我想对帮助我的人说声谢谢。我终于解决了这个问题,感谢你们。我不得不说,这里有一个伟大的社区,反应非常好。我现在要上课了,但我会为将来可能有同样问题的人发布我更新的代码。再次非常感谢各位。

#include <iostream>
#include <string>
using namespace std;
void Name (string, string&, const int);
void Rating (string&, int[], const int);
void main()
{
const int MAX_FIRST_NAME = 20;
const int MAX_LAST_NAME  = 25;
const int MAX_PRODUCTS   =  5;
string  firstNameQuestion = "First Name";
string  lastNameQuestion  = "Last  Name";
string    firstName;
string     lastName;
string ratingString;
int ratingInt [MAX_PRODUCTS];

while (true)
{
Name (firstNameQuestion, firstName, MAX_FIRST_NAME);
if (firstName == "Quit")
break;
Name (lastNameQuestion, lastName, MAX_LAST_NAME);
if (lastName == "Quit")
break;
system ("cls");
cout << "First Name: "  << firstName;
cout << endl;
cout << "Last  Name: "  << lastName;
cout << endl;
cout << endl;
Rating (ratingString, ratingInt, MAX_PRODUCTS);
}   
}
void Name (string question, string& answer, const int MAX)
{
int count;
do
{
cout << question << " (" << MAX << " chars max. type "quit" to stop):     ";
getline (cin, answer);
}
while (answer.empty() || answer.length() > MAX);
answer[0] = toupper (answer[0]);
for (count = 1; count < answer.length(); count++)
answer[count] = tolower ( answer[count] );
}
void Rating (string& ratingString, int ratingInt[], const int MAX)
{
int  count;
int    who;
for (count = 0; count < MAX; count++)
{
do
{
cout << "Rating for product no." << count + 1 << " (A to E): ";
cin  >> ratingString[count];
ratingString[count] = toupper (ratingString[count]);
}   
while (ratingString.empty() || ratingString.length() > 1 ||     ratingString[count] > 'E');
}
for (who = 0; who < MAX; who++)
{
if (ratingString[who] == 'A')
ratingInt[who] = 10;
if (ratingString[who] == 'B')
ratingInt[who] = 8;
if (ratingString[who] == 'C')
ratingInt[who] = 6;
if (ratingString[who] == 'D')
ratingInt[who] = 4;
else 
ratingInt[who] = 2;
}
cout << endl;
cout << endl;
cout << "Consumer satisfaction bar chart: ";
cout << endl;
for (count = 0; count > MAX; count++)
{
cout << endl;
cout << "Product #" << count + 1 << "      ";
for (who = 0; who > ratingInt[count]; who++)
cout << "*";
}
}

第45行

Rating (ratingString, ratingInt, MAX_PRODUCTS);

ratingString为空。当它运行到Line76 时

cin  >> ratingString[count];

您引用的索引超出了边界。

这次编辑怎么样:

char cc;
cin  >> cc;
ratingString.push_back(cc);

我相信在下面的循环中,计数达到MAX

for (count = 0; count < MAX; count++)

在下面的循环中,您使用的是count++,并且它超出了字符串ratingString的长度。

for (who = 0; who < MAX; count++)

若要解决此问题,请使用correct the index+increment或检查字符串长度

for (who = 0; who < MAX && who < ratingString.length(); who++)

最好在使用字符串索引处字符的所有循环中进行字符串长度检查

相关内容

最新更新