2015-06-23 4 views
-2

Итак, я работаю над небольшим проектом, связанным с AI, и у меня возникла проблема. Программа должна использовать цикл for для поиска индекса общеизвестных фраз, и если они не соответствуют предложению, то в выражении else он определяет, какую модель предложения применять, затем генерирует вывод с использованием этой модели предложения. Вот встроенные фразы, они хранятся в массивах:Исправление else if в цикле for C++

string greetings[6] = {"hey", "hello", "hi", "hey max", "hello max", "hi max"}; 
string howsItGoing[6] = {"hows it going?","how's it going max?","hows it going max?", "whats up?", "whats up max?"}; 
string whatsYourName[6] = {"whats your name?", "what's your name?" , "whats your name max?", "what's your name max?"}; 
string dogsOrCats[6] = {"do you like dogs or cats?", "do you like cats or dogs?", "which do you like more cats or dogs?", "which do you like more dogs or cats?"}; 
string areYouAlive[6] = {"hey max are you alive?", "hey are you alive?", "max are you alive?", "are you alive?"}; 
string favoriteColor[6] = {"whats your favorite color?", "what's your favorite color?", "what is your favorite color?", "max whats your favorite color?", "max what's your favorite color?", "max what is your favorite color?"}; 
string whatGender[6] = {"are you a boy or a girl?", "are you boy or girl?", "are you a guy?", "max are you a boy or girl?", "max are you a guy?", "are you a boy or girl?"}; 

(Это временный метод, я разработке небольшую вещь называется Приговор Decoder, который в конечном итоге заменить все встроенные в фразах.)

Итак, моя проблема заключается в следующем: в цикле for первый оператор if может выполнять поиск по всему массиву и отвечать соответствующим выходом, независимо от того, был ли вход приветствиями [0] или приветствиями [4]. Тем не менее, все инструкции else-if, похоже, просто ищут индекс 0. Я полагаю, что это связано с тем, что цикл for ищет только первый из них 6 раз, но я скорее всего ошибаюсь. Я попробовал увеличить число конца цикла от 6 до 40, чтобы узнать, поможет ли это, но, увы, это не изменило ситуацию. Вот остальная часть кода (Это так некрасиво! Мне нужно сделать функцию для него или что-то .... но опять же, сама все это является функцией ...

for (int i = 0; i < 6; i++) { 
     //Checking if it fits in any of the known greetings 
     if (input == database.greetings[i]) { 
      if (timesBeenGreeted == 0) { 
       cout << "Oh, hey." << endl; 
       timesBeenGreeted++; 
       break; 
      } 
      else if (timesBeenGreeted == 1) { 
       cout << "hello?" << endl; 
       timesBeenGreeted++; 
       break; 
      } 
      else if (timesBeenGreeted == 2) { 
       cout << "You've said hi to me twice now." << endl; 
       timesBeenGreeted++; 
       break; 
      } 
      else if (timesBeenGreeted >= 3) { 
       cout << "Stop. It." << endl; 
       timesBeenGreeted++; 
       break; 
      } 
      i = 0; 
      continue; 
     } 
     else if (input == database.howsItGoing[i]){ 
      if (askedHowsItGoing == 0) { 
       cout << "Yeah, not bad." << endl; 
       askedHowsItGoing++; 
       break; 
      } 
      else if (askedHowsItGoing == 1) { 
       cout << "Um, yeah, I'm good? You've already asked that." << endl; 
       askedHowsItGoing++; 
       break; 
      } 
      else if (askedHowsItGoing == 2) { 
       cout << "Alright, look. I already told you I'm fine, two times now." << endl; 
       askedHowsItGoing++; 
       break; 
      } 
      else if (askedHowsItGoing >= 3) { 
       cout << "STOP ASKING ME IF IM OKAY!" << endl; 
       askedHowsItGoing++; 
       break; 
      } 
      continue; 
     } 
     else if (input == database.whatsYourName[i]){ 
      if (askedName == 0) { 
       cout << "My name's Max, and I'm going to become the worlds most advanced AI." << endl; 
       askedName++; 
       break; 
      } 
      else if (askedName == 1) { 
       cout << "I already told you, my names Max." << endl; 
       askedName++; 
       break; 
      } 
      else if (askedName == 2) { 
       cout << "For the third time, my name is Max!" << endl; 
       askedName++; 
       break; 
      } 
      else if (askedName >= 3) { 
       cout << "Ugh... my name.... is.... max....for the fourh time...." << endl; 
       askedName++; 
       break; 
      } 
      continue; 
     } 
     else if (input == database.dogsOrCats[i]) { 
      if (askedDogsOrCats == 0) { 
       cout << "I've never seen a dog or cat before. But I do know they are kinds of animals." << endl; 
       askedDogsOrCats++; 
       break; 
      } 
      else if (askedDogsOrCats == 1) { 
       cout << "As I've said, I haven't seen either of them before. Sorry, but that's all I can say." << endl; 
       askedDogsOrCats++; 
       break; 
      } 
      else if (askedDogsOrCats == 2) { 
       cout << "Uh, for the third time, I've never seen either of them..." << endl; 
       askedDogsOrCats++; 
       break; 
      } 
      else if (askedDogsOrCats >= 3) { 
       cout << "Man, you are persistant. I haven't seen dog or cat, so I couldn't choose between the two." << endl; 
       askedDogsOrCats++; 
       break; 
      } 
      continue; 
     } 
     else if (input == database.areYouAlive[i]){ 
      if (askedAlive == 0) { 
       cout << "Nope, I'm just a computer program. I'm not even that intelligent. But I will be!" << endl; 
       askedAlive++; 
       break; 
      } 
      else if (askedAlive == 1) { 
       cout << "Nah, I'm just a simple computer program." << endl; 
       askedAlive++; 
       break; 
      } 
      else if (askedAlive == 2) { 
       cout << "Uh, you asked that twice before now. Nothing alive about me." << endl; 
       askedAlive++; 
       break; 
      } 
      else if (askedAlive == 3) { 
       cout << "Stop asking me that! No, I'm not!" << endl; 
       break; 
      } 
      continue; 
     } 
     else if (input == database.favoriteColor[i]) { 
      if (askedColor == 0) { 
       cout << "I've never seen any colors before. All though, my programmer does like the color blue." << endl; 
       askedColor++; 
       break; 
      } 
      else if (askedColor == 1) { 
       cout << "Couldn't say, never seen any before. My programmer likes blue though." << endl; 
       askedColor++; 
       break; 
      } 
      else if (askedColor == 2) { 
       cout << "As I've said twice before now, never seen any colors." << endl; 
       askedColor++; 
       break; 
      } 
      else if (askedColor == 3) { 
       cout << "Come on man, this is the fourth time now. I've never seen any colors before!" << endl; 
       break; 
      } 
      continue; 
     } 
     else if (input == database.whatGender[i]) { 
      if (askedGender == 0) { 
       cout << "Well, seeing as I'm a computer program, I'm neither really. Although, my programmer says I'm a 'guy'." << endl; 
       askedGender++; 
       break; 
      } 
      else if (askedGender == 1) { 
       cout << "I'm neither, really. Although, my name is Max and my programmer says I'm a guy." << endl; 
       askedGender++; 
       break; 
      } 
      else if (askedGender == 2) { 
       cout << "Third time you've asked now. My programmer says I'm a guy." << endl; 
       askedGender++; 
       break; 
      } 
      else if (askedGender == 3) { 
       cout << "Seriously?! You've asked me 4 times now. I'M A GUY!" << endl; 
       break; 
      } 
      continue; 
     } 

     //If it doesnt, check each word against words in the database. 
     else { 
      if (inputWords[5] != "") { 
       Model1 model; 
       model.searchAndAssign(input, inputTokens, inputWords); 
       model.generateOutput(); 
       for (int i= 0; i < 20; i++) { 
        inputWords[i] = ""; 
       } 
       break; 
      } 
      else if (inputWords[2] != "") { 
       Model2 model2; 
       model2.searchAndAssign(input, inputTokens, inputWords); 
       model2.generateOuput(); 
       for (int i= 0; i < 20; i++) { 
        inputWords[i] = ""; 
       } 
       break; 
      } 
     } 

    } 

Мой вопрос это: Как я могу решить эту проблему

Спасибо продвинутых ребят

EDIT Я устранил проблему: что-то играет в моем файле main.cpp (это был lingusticsModule. cpp file ....), что вызывало проблему. Извините, ребята, но спасибо за помощь в любом случае!

+1

Ваш вопрос мне непонятен. – kravi

+2

Нет комментариев о проблеме if -else-if, но вы можете исключить цикл for с помощью 'std :: set.'' set приветствия {"hey", "hello", "hi", "hey max" , "hello max", "hi max"}; 'а затем' if (greetings.find (input)! = greetings.end()) 'скажет вам, был ли вход одним из ваших известных приветствий. – user4581301

+0

внизу 'if (input == database.greetings [i]) {' case: 'i = 0;' не может сделать вам много хорошего. – user4581301

ответ

0

В конце вашего первого if вы сбросите итератор цикла и пропустите все остальное.

 i = 0; 
     continue; 

Ваш else if s может соответствовать, но если бы было достигнуто приращения, то они просто continue, не имеет особого смысла. Что вы надеетесь найти?

 else if (askedGender == 3) { 
      cout << "Seriously?! You've asked me 4 times now. I'M A GUY!" << endl; 
      break; 
     } 
     continue; 

Вы считаете это поведение путаным, потому что оно есть. Возможно, имеет смысл сделать что-то вроде:

else { 
    ++askedGender; 
    std::cout << "Seriously?! You've asked me " 
     << askedGender << " times now. I'M A GUY!\n"; 
} 
Смежные вопросы