이 C++ 프로그램을 작성 중입니다. try catch catch 예외 처리를 사용해야합니다. 내 프로그램이 컴파일됩니다. 그러나 mouse
을 (를) 찾을 수 없습니다. 실제로 찾을 수없는 단어 laptop
이어야합니다. for
루프 내에서 throw
코드를 for
루프 외부로 이동했습니다. 그러나 이것은 결과가 예상대로 수정되지 않았습니다. 함수 getProductID()
에 throw 코드를 사용하는 것이 가장 논리적 인 것 같습니다. 그러나 프로그램의 다른 부분에 있어야할까요?C++ 함수에서 캐치를 시도 하시겠습니까?
#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;
}
사용'표준 : find'. 또한 마술처럼 코드를 수정합니다. 특히 함수에 전달할 때 원시 배열을 사용하지 않아야합니다. 'std :: array'는 크기를 알고 효율적으로 수행합니다. – chris
일부 표준을 던져주세요 : 예외 - 던지기 std :: string 못생긴 –
팁 Dieter 주셔서 감사. 나는 이것을 배우는 데 새로운 사람이다. std :: string을 throw하는 예제를 줄 수 있습니까? :: std :: string을 throw합니까? – user2972340