我正在研究这个 C++ 程序。我需要使用 try throw catch 异常处理。我的程序编译。但是,它返回mouse
未找到。事实上,它应该是laptop
不应该被发现的词。我已将throw
代码从循环内移到for
循环外for
。但这并没有将结果固定为预期的那样。在函数中包含 throw 代码似乎最合乎逻辑getProductID()
,但也许它应该在程序的另一部分?
#include<iostream>
#include<string>
using namespace std;
int getProductID(int ids[], string names[], int numProducts, string target)
{
for(int i=0; i< numProducts; i++)
{
if (names[1] == target)
return ids[i];
}
throw(target);
}
int main() //Sample code to test the getProductID function
{
int productIds[] = {4,5,8,10,13};
string products[] = {"computer", "flash drive","mouse","printer","camera"};
try
{
cout<< getProductID(productIds, products, 5, "mouse")<<endl;
cout<< getProductID(productIds, products, 5, "camera")<<endl;
cout<<getProductID(productIds, products, 5, "laptop")<<endl;
}
catch(string str)
{
cout<<"Error: "<< str<< " product not found."<< endl;
cout<<"End of program."<<endl;
return 0;
}
return 0;
}