我需要让用户输入8个邮政编码,然后将它们存储在一个整数数组中,然后逐个输出,每个都在一个新的行中。这两件事应该在不同的函数中完成。但是当它第一次运行代码时它只显示菜单,然后第二次循环,当我输入L并输入8个zipcodes时显示此错误 输入您的选择:libc ++ abi.dylib:以类型为std :: out_of_range的未捕获异常终止:basic_string(此处为optionInChar = optionInString.at(0);)
using namespace std;
void DisplayCityZipCodes();
int LoadCityZipCodes(int ZipCodes[],int SIZE);
void DisplayCityZipCodes(int ZipCodes[],int SIZE);
void DisplayMenu();
char GetOption();
int main(){
int const SIZE=8;
int ZipCodes[SIZE]={0};
bool moreWork=true;
option=GetOption();
while(moreWork) {
DisplayMenu();
option=GetOption();
switch(option){
case 'L':
ZipCodes[SIZE]= LoadCityZipCodes(ZipCodes, SIZE);
break;
cout<<"D";
case 'D': DisplayCityZipCodes(ZipCodes, SIZE);
break;
}
}
}
void DisplayMenu(){
cout<<" **********************\n\n";
cout<<" San Jose City Zip codes\n\n";
cout<<" **********************\n\n";
cout<<"1. Load City zip codes\n";
cout<<"2. Display all City zip codes\n";
cout<<"3. Search a City zip code\n";
cout<<"4. Reverse the City zip code List\n";
cout<<"5. Quit\n";
}
char GetOption(){
string optionInString="";
char optionInChar='a';
cout<<"\n\nEnter your choice: ";
getline(cin,optionInString);
optionInChar=optionInString.at(0);
cout<<"\n";
return optionInChar;
}
int LoadCityZipCodes(int ZipCodes[],int SIZE){
cout<<"PLease enter 8 city Zip Codes ";
int i=0;
for(;i<8;i=i+1){
cin >>ZipCodes[i];
}
return ZipCodes[i];
}
void DisplayCityZipCodes(int ZipCodes[],int SIZE){
int i=0;
for(;i<8;i=i+1){
cout<<ZipCodes[i]<<endl;
}
}
答案 0 :(得分:2)
现在我已经很长时间没有使用过C ++了,但是这样可行。 您应该查看变量声明和其他一些内容。
#include<iostream>
#include<conio.h>
using namespace std;
void DisplayCityZipCodes();
void LoadCityZipCodes();
void DisplayMenu();
int const SIZE = 8;
int ZipCodes[SIZE];
int main()
{
DisplayMenu();
return 0;
}
void DisplayMenu()
{
int ch;
cout << " **********************\n\n";
cout << " San Jose City Zip codes\n\n";
cout << " **********************\n\n";
do
{
cout << "1. Load City zip codes\n";
cout << "2. Display all City zip codes\n";
cout << "3. Search a City zip code\n";
cout << "4. Reverse the City zip code List\n";
cout << "5. Quit\n";
cout << "\nPlease enter your choice:";
cin >> ch;
switch (ch)
{
case 1:
LoadCityZipCodes();
break;
case 2:
DisplayCityZipCodes();
break;
case 5:
exit(0); //You will need to include math.h for this.
default:
cout << "please enter a proper choice!";
break;
}
} while (1);
}
void LoadCityZipCodes()
{
cout << "PLease enter 8 city Zip Codes ";
for (int i=0; i<8; i++)
{
cin >> ZipCodes[i];
}
}
void DisplayCityZipCodes()
{
for (int i=0; i<8; i++)
{
cout << ZipCodes[i] << endl;
}
}
您可以使用案例3和4添加剩余的功能。 在发布之前尝试调试代码并查看它是如何工作的:)
答案 1 :(得分:1)
您需要仔细查看陈述
return ZipCodes[i];
和
ZipCodes[SIZE]= LoadCityZipCodes(ZipCodes, SIZE);
在这两种情况下,您使用的ZipCodes[8]
肯定超出了范围。
要解决这两个问题,请不要从LoadCityZipCodes
返回任何内容(即返回void
),因为它已经设置了数组中的值。
答案 2 :(得分:0)
你需要记住,在编程时我们从0开始计数。这意味着对于大小为8的数组,所有有效索引都是:0,1,2,3,4,5,6,7。当你尝试使用ZipCodes [8]访问你的数组,你要求的第9个元素超出范围。