我正在研究这个C ++程序。我需要使用try throw catch异常处理。我的程序编译。但是,它返回mouse
未找到。实际上它应该是不应该找到的laptop
这个词。我已将throw
代码从for
循环移到for
循环之外。但这并没有解决结果如预期的那样。在函数getProductID()
中使用throw代码似乎最合乎逻辑,但也许它应该在程序的另一部分中?
#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;
}
答案 0 :(得分:5)
将1
替换为i
以迭代数组中的所有项目:
if (names[1] == target)
^
答案 1 :(得分:1)
您还可以使用C ++标准工具来提高代码的效率。最好创建一个结构来将id及其名称存储在一个单元中:
struct Product
{
int id;
std::string name;
};
此外,您最好从std::exception
throw
例外
struct TargetNotFound : public std::exception
{
TargetNotFound(const std::string &target) : target(target) {}
std::string getTarget() const
{
return target;
}
private:
const std::string target;
};
而且,您可以使用std::vector
和std::find_if
代替循环:
int getProductID(const std::vector<Product> &p, const std::string &target)
{
auto i = std::find_if(p.begin(), p.end(), [&](const Product &x)
{
return x.name==target;
});
if (i == p.end())
throw TargetNotFound(target);
else
return i->id;
}
最后,您的主要内容可能是:
int main()
{
std::vector<Product> products
{
{4, "computers"},
{5, "flash drive"},
{8, "mouse"},
{10, "printer"},
{13, "camera"},
};
try
{
cout<< getProductID(products, "mouse")<<endl;
cout<< getProductID(products, "camera")<<endl;
cout<<getProductID(products, "laptop")<<endl;
}
catch(const TargetNotFound &ex)
{
cout<<"Error: "<< ex.getTarget() << " product not found."<< endl;
cout<<"End of program."<<endl;
}
}
答案 2 :(得分:0)
#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;//once exception is
//throw by this function call it goes to catch block after that it does not execute
//following line
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;
}
一旦异常被跟随函数调用抛出,它就会在它执行其他行之后进入catch块
cout<< getProductID(productIds, products, 5, "mouse")<<endl;