私はこのC++プログラムに取り組んでいます。try throw catch 例外処理を使用する必要があります。私のプログラムはコンパイルされます。ただし、mouse
見つかりませんでした。実際にはlaptop
見つからないはずの単語であるべき場合。throw
コードをループ内からfor
ループ外に移動しましたfor
。しかし、これは結果を期待どおりに修正しませんでした。関数内にスロー コードを配置するのが最も論理的と思わ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;
}