2013-11-09 2 views
0

이 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; 

} 
+1

사용'표준 : find'. 또한 마술처럼 코드를 수정합니다. 특히 함수에 전달할 때 원시 배열을 사용하지 않아야합니다. 'std :: array'는 크기를 알고 효율적으로 수행합니다. – chris

+2

일부 표준을 던져주세요 : 예외 - 던지기 std :: string 못생긴 –

+0

팁 Dieter 주셔서 감사. 나는 이것을 배우는 데 새로운 사람이다. std :: string을 throw하는 예제를 줄 수 있습니까? :: std :: string을 throw합니까? – user2972340

답변

5

배열의 모든 항목을 반복하는 i에 의해 1 교체 :

if (names[1] == target) 
     ^
+0

내가 간과 한 M. M. Typo 고맙습니다. .... – user2972340

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; 

} 

을 제외하고는 함수가 호출 따라 던져 인은 다른를 실행하지 않습니다 그 후 블록을 잡으려고 이동하면 line cout<< getProductID(productIds, products, 5, "mouse")<<endl;

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을 사용할 수 있으며

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; 
} 

마지막으로, 메인이 될 수있는 일이 같은 : 대신 루프의 std::find_if

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; 
    } 
} 

Live code

관련 문제