Program having unexpected output

Asked

Viewed 59 times

0

I’m having an unexpected output problem and can’t find the error in my code, the output in question is the errors of all sentences which are not "Dog walks." , a notorious observation is the fact that if the user enters with "Dog" enter "anda" enter "." enter, the program will only accuse NOT OK at the end of "." However, when we put any other sentences that are not the same quoted, in the first enter I already get the result "Not ok". Ex: "Fish" enter, (Not ok printed), "Nothing", enter, (not ok printed), "." , enter, (not ok again).

#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;

vector<string> nome;
vector<string> verbo;     
vector<string> conjuncao;

void inicializar(){     // Função pra definir valores dos vetores  
nome.push_back("cachorro");
nome.push_back("passaro");
nome.push_back("peixe");

verbo.push_back("anda");
verbo.push_back("nada");
verbo.push_back("voa");

conjuncao.push_back("e");
conjuncao.push_back("ou");
conjuncao.push_back("mas");

}

bool isName(string v){
    for(int x = 0; x<nome.size(); x++){   //Verifica se a primeira palavra é um nome
       if(nome[x] == v) return true; 
       return false;
    }
}

bool isVerb(string v){
    for(int x = 0; x<verbo.size(); x++){
        if(verbo[x] == v) return true;  //Verifica se a segunda palavra é um verbo
         return false;
    }
}
bool isConjuncao(string v){
    for(int x = 0; x<conjuncao.size(); x++){
      if(conjuncao[x]==v) return true;   //Verifica se a segunda palavra é uma conj
      return false;
    }
}

bool sentenca(){  //Insere e faz todas as verificações

 string v;
 cin >> v;
 if(!isName(v)) return false;

 string v2;
 cin >> v2;
 if(!isVerb(v2)) return false;

 string v3;
 cin >> v3;
 if(v3 == ".") return true;  //Se for ".", termina, senão, continua.
 if(!isConjuncao(v3)) return false;

 return sentenca();

}



int main()
{
inicializar();

while(cin){  //Cria um loop para repetir o processo.
  bool b = sentenca();
    if(b) cout << "OK" << endl;  //Caso true, "ok"
    else cout << "Not ok" << endl;
}
    return 0;
}

1 answer

2


1) All three verification methods are wrong.

You should put the "Return false" out of the loop for and not inside. Because only if it doesn’t find it inside will it return false.

2) Sentence should not be recursive...

Why is sentence a method that calls itself? You’re looping while already in the main function. It is better to return false if you do not find a true return.

  • Opa friend, thanks for the answer. First of all, really, had not even noticed the keys (a really silly bug hehe). Second, he calls himself if v3 was not a point but a "But", "and", "Or", starting the whole process again. " Dog walks BUT fish nothing".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.