2017-04-04 64 views
0

如何分離以下語句,以便我還可以顯示"123"搜索的信息,而不顯示"topic not supported",因爲它不是從第一次搜索開始的"decimals"我將如何分離這些陳述?

string sentence; 
string search; 
string sentence2; 
string search2; 
size_t position2; 

cin >> choosetopic; 

switch (choosetopic) 
{ 
    case 1: 
     cout << "Please enter the name of the topic you need help with."; 

     cin >> sentence; 
     system("cls"); 

     cout << "Topic: " << sentence << endl; 
     cout << "\n"; 

     size_t pos; 
     search = "Decimals"; 
     search = "decimals"; 
     search = "decimal"; 
     search = "Decimal"; 
     pos = sentence.find(search); 
     if (pos != std::string::npos) 
      cout << "blah blah" << std::endl; 
     else 
      cout << "Topic not yet supported, please try another. View 'Help' on the main menu to see supported topics. " << endl; 

     cin >> sentence; 
     cout << "Topic: " << sentence << endl; 
     cout << "\n"; 
     search = "123"; 
     pos = sentence.find(search); 
     if (pos != std::string::npos) 
      cout << "12313" << std::endl; 
     else 
      cout << "Topic not yet supported, please try another. View 'Help' on the main menu to see supported topics. " << endl; 
+2

那些分配'search'不會追加或導致'find'調用搜索多個字符串。 –

+0

我怎麼能這樣做呢? – James941

+0

對於初學者來說,如果你發現「小數」,你會發現「小數」,所以後者是多餘的。 – chris

回答

0

嘗試一些更喜歡這個:

int containsTopic(const std::string &s, const char **topics, int numTopics) 
{ 
    for(int i = 0; i < numTopics; ++i) 
    { 
     if (s.find(topics[i]) != std::string::npos) 
      return i; 
    } 
    return -1; 
} 

std::string sentence; 
int choosetopic; 

std::cin >> choosetopic; 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

switch (choosetopic) 
{ 
    case 1: 
    { 
     std::cout << "Please enter the name of the topic you need help with."; 

     std::cin >> sentence; 
     std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
     // better: std::getline(std::cin, sentence); 

     system("cls"); 

     std::cout << "Topic: " << sentence << std::endl; 
     std::cout << "\n"; 

     char* search[] = {"Decimal", "decimal", "123"}; 

     int idx = containsTopic(sentence, search, 3); 
     switch (idx) 
     { 
      case 0: 
      case 1: 
       std::cout << "blah blah" << std::endl; 
       break; 

      case 2: 
       std::cout << "12313" << std::endl; 
       break; 

      default: 
       std::cout << "Topic not yet supported, please try another. View 'Help' on the main menu to see supported topics. " << std::endl; 
       break; 
     } 

     //... 

     break; 
    } 

    //... 
}