作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我搜索了网站,但找不到解决问题的方法。我尝试进行微小的更改,但没有解决任何问题。我不断收到“字符串下标超出范围”错误。我不知道为什么。也许我是盲人,我在某处遗漏了一个小错误。现在我在这里请求帮助。
程序信息:该程序将输入名字和姓氏,对其进行验证并应用大小写转换。用户输入名字和姓氏后,它将清除屏幕并显示用户输入的名字。然后它会输入产品评级,对其进行验证并应用大小写转换。显示一个标题,后跟一个与 5 个产品值(value)相对应的条形图。
编辑:我想对帮助过我的人说声谢谢。谢天谢地,我终于解决了这个问题。我不得不说这里有一个很棒的社区,而且 react 非常好。我现在要去上课,但我会为将来可能遇到同样问题的人发布我更新的代码。再次非常感谢你们。
#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);
关于c++ - 我得到一个 "string subscript out of range error"。我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13577820/
我是一名优秀的程序员,十分优秀!