Code for earlier than expected

2

Follow the code with my suspicions:

Header:

    class Name_pairs
{
public:
    void read_names();
    void read_ages(); 
    void print() const; 
    void sort(); // Ordenar os nomes com as idades        

private:
    std::vector<std::string>name;
    std::vector<double>age;    
};

#endif 

Implementation:

void Name_pairs::read_names()
{
    cout << "Entre com os nomes desejados, digite 'SemNome' para finalizar a lista." << endl;
    string NomesVetor; 

    while (cin >> NomesVetor && NomesVetor != "SemNome")
    {
        for (size_t x = 0; x < name.size(); ++x) // confere se há nomes duplicados 
        {
            if (name[x] == NomesVetor) cout << "Nome repetido." << endl;
            name.push_back(NomesVetor);
        }
    }
}

void Name_pairs::read_ages()
{
    for (size_t x = 0; x < name.size(); ++x)
    {
        cout << "Nome de " << name[x] << ": " << endl;
        double IdadesVetor;
        cin >> IdadesVetor;
        age.push_back(IdadesVetor);
    }
}

void Name_pairs::print() const                                                                                                                      
{
    for (size_t x = 0; x < name.size(); ++x)
    {
        cout << "Nome: " << name[x] << ", Idade: " << age[x] << endl;
    }
} 

void Name_pairs::sort() 
{
    vector<string> strCopia = name;
    vector<double> dbCopia = age; 

    std::sort(begin(name), end(name)); 

    for (size_t x = 0; x < name.size(); ++x)
    {
        for (size_t y = 0; y < name.size(); ++y)
        {
            if (name[x] == strCopia[y]) age[x] = dbCopia[y];

        }
    }
}

Main:

using namespace std;

int main()
{
    Name_pairs objeto;
    objeto.read_names();
    objeto.read_ages();



    system("pause");
    return 0;
}

The error is when I enter the names and end the entry by typing 'NoName', the program simply closes. I'm afraid that the error is in the Read_names() function that may not be giving continuity to read_ages() or in Main.cpp itself, since I'm now starting the classes and I do not quite understand the calls yet.     

asked by anonymous 30.06.2016 / 20:14

1 answer

3

The problem lies in this line:

name.push_back(NomesVetor);

She is in the wrong place and is not adding anything since she only adds if it is a repeated name, which is not what she wants and should not be testing it. So:

while (cin >> NomesVetor && NomesVetor != "SemNome") {
    for (size_t x = 0; x < name.size(); ++x) { // confere se há nomes duplicados 
         if (name[x] == NomesVetor) cout << "Nome repetido." << endl;
    }
    name.push_back(NomesVetor);
}

See running on ideone .

Notice that it is reporting that it is repeating and is not preventing it. You may be missing a continue there.

The code as a whole is not quite the way you usually do it, but this is another problem.

    
30.06.2016 / 20:44