Начальная сложность C++почему этот цикл завершается раньше?

Этот код представляет собой простое упражнение для наследования классов и виртуальных функций. Класс случая «человек» является производным от сотрудника, зависимого, работника и менеджера. Код должен отображать экран ввода, на котором пользователь может ввести данные для 10 человек, которые различаются в зависимости от того, для какого типа лица пользователь вводит данные. Затем, когда пользователь ввел необходимые данные, нажатие клавиши, отличной от 1, 2, 3, 4 или 5, приведет их к меню дисплея, где они смогут выбрать, какую информацию они хотят видеть.

Проблема: первый цикл for в main() работает нормально, и данные можно вводить до 10 раз. Однако следующий цикл (цикл отображения) отображает меню, а затем сразу же завершает работу, не прочитав решение пользователя. Я не могу понять, почему это происходит. Он даже пропускает мой небольшой тестовый ввод в конце, он просто выходит из программы?

Разве он не должен отображать меню, затем ждать ввода пользователя, а затем продолжать или завершать цикл?

main.cpp

using namespace std;

#include "person.h"
#include <iostream>

using namespace std;

int main()
{

    worker w;
    employee e;
    dependent d;
    manager m;
    person p;

    int decision;


    for (int i=0; i<10; i++)
    {
        cout << "To enter employee information, press 1." << endl;
        cout << "To enter dependent information, press 2." << endl;
        cout << "To enter manager information, press 3." << endl;
        cout << "To enter worker information, press 4." << endl;
        cout << "To edit information for a person who is none of the above, press 5." << endl;
        cout << "To display entered information, press anything else." << endl;
        cin >> decision;
        if (decision==1)             //employee
        {
            e.obtain();
        }
        else if (decision==2)       //dependent
        {
            d.obtain();
        }
        else if (decision==3)         //manager
        {
            m.obtain();
        }
        else if (decision==4)        //worker
        {
            w.obtain();
        }
        else if (decision==5)        //other person
        {
            p.obtain();
        }
        else
        {
            break;
        }

    };

    for (int i=0; i<10; i++)

    {
        cout << "To display employee information, press 1." << endl;
        cout << "To display dependent information, press 2." << endl;
        cout << "To display manager information, press 3." << endl;
        cout << "To display worker information, press 4." << endl;
        cout << "To display information for a person who is none of the above, press 5." << endl;
        cout << "To exit, press anything else" << endl;
        cin >> decision;
        if (decision==1)             //employee
        {
            e.display();
        }
        else if (decision==2)       //dependent
        {
            d.display();
        }
        else if (decision==3)         //manager
        {
            m.display();
        }
        else if (decision==4)        //worker
        {
            w.display();
        }
        else if (decision==5)        //other person
        {
            p.display();
        }
        else
        {
            break;
        }
    }

    int test;
    cin >> test;
    return 0;
}

человек.ч

#ifndef PERSON_H
#define PERSON_H

#include <iostream>
#include <string>

using namespace std;

struct date                       //Structures defining date display and SSN display
    {                             //e.g. 3/12/14, XXX-XX-XXXX
        int day;
        int month;
        int year;
    };
struct SSN
    {
        int dig123;
        int dig45;
        int dig6789;
    };


class person                     //Base class
{
public:
    person();
    virtual ~person();
    virtual void obtain ();
    virtual void display();

protected:
    string name;
    char gender;
    date dob;                     //Date of Birth
    SSN ssn;
    string address;
    int phone;
};


class employee: public person   //Employee derived class
{
public:
    employee();
    ~employee ();
    void obtain();
    void display();
private:
    date doh;               //Date of Hire
    int salary;
    string location;
    int workphone;
};

class dependent: public person   //Dependent derived class
{
public:
    dependent();
    ~dependent();
    void obtain();
    void display();
private:
    string address;
    SSN ssn2;                    //SSN of employee of dependent

};

class manager: public person    //Manager derived class
{
public:
    manager();
    ~manager();
    void obtain();
    void display();
private:
    string title;
};

class worker: public person
{
public:
    worker();
    ~worker();
    void obtain();
    void display();
private:
    string project;
};


#endif // PERSON_H

человек.cpp

#include "person.h"

person::person()
{

}

person::~person()
{

}

void person::obtain ()
{

    cout<<"Please enter information about the individual:" << endl;
    cout<< "Name:" << endl;
    getline (cin, name);
    getline (cin, name);
    cout<< "Gender (m or f): "<< endl;
    cin>> gender;
    cout<< "Date of Birth: Day? " << endl;
    cin>> dob.day;
    cout<< "Date of Birth: Month? " << endl;
    cin>> dob.month;
    cout<< "Date of Birth: Year? " << endl;
    cin>> dob.year;
    cout<< "Address: "<< endl;
    getline (cin, address);
    getline (cin, address);
    cout<< "Phone number: " << endl;
    cin>> phone;
    cout<< "First three digits of SSN: " << endl;
    cin>> ssn.dig123;
    cout<< "Next 2 digits of SSN: " << endl;
    cin>> ssn.dig45;
    cout<< "Final 4 digits of SSN: " << endl;
    cin>> ssn.dig6789;
}
void person::display()
{
    cout<< "Name: " << name << endl;
    if (gender=='m')
    {
        cout<<"Gender: "<<gender<< endl;
    }
    else if (gender=='f')
    {
        cout<<"Gender: "<< gender<<endl;
    }
    else
    {
        cout<<"You did not enter male(m) or female(f) as a gender."<<endl;
    }
    cout << "Date of Birth: " << dob.month << "/" << dob.day <<"/" << dob.year << endl;
    cout << "Address: " << address << endl;
    cout << "Phone number: " << phone << endl;
    cout << "SSN: " << ssn.dig123 << "-" << ssn.dig45 << "-" << ssn.dig6789 << endl;
}

employee::employee():person()
{

}

employee::~employee()
{

}


void employee::obtain()
{
    person::obtain();
    cout<< "Date of Hire: Day? " << endl;
    cin>> doh.day;
    cout<< "Date of Hire: Month? " << endl;
    cin>> doh.month;
    cout<< "Date of Hire: Year? " << endl;
    cin>> doh.year;
    cout<< "Salary: $" << endl;
    cin >> salary;
    cout<< "Location: "<< endl;
    getline (cin, location);
    getline (cin, location);
    cout<< "Work phone number: " << endl;
    cin>> workphone;
}

void employee::display()
{
    person::display();
    cout << "Date of Hire: " << doh.month << "/" << doh.day <<"/" << doh.year << endl;
    cout << "Location: " << location << endl;
    cout << "Work phone number: " << workphone << endl;
}

dependent::dependent(): person()
{

}

dependent::~dependent()
{

}

void dependent::obtain()
{
    person::obtain();
    cout << "SSN of employee of which this person is a dependent:" << endl;
    cout<< "First three digits of SSN: " << endl;
    cin>> ssn2.dig123;
    cout<< "Next 2 digits of SSN: " << endl;
    cin>> ssn2.dig45;
    cout<< "Final 4 digits of SSN: " << endl;
    cin>> ssn2.dig6789;
    cout << "Address (if different from employee's address): " << endl;
    cout<< "Address: "<< endl;
    getline (cin, address);
    getline (cin, address);

}

void dependent::display()
{
    person::display();
    cout<< "Address: " << address << endl;
    cout << "SSN of employee: " << ssn2.dig123 << "-" << ssn2.dig45 << "-" << ssn2.dig6789 << endl;
}

worker::worker():person()
{

}
worker::~worker()
{

}

void worker::obtain()
{
    person::obtain();
    cout << "Project: " << endl;
    getline (cin, project);
}

void worker::display()
{
    person::display();
    cout << "Project: " << project << endl;
}

manager::manager():person()
{

}

manager::~manager()
{

}

void manager::obtain()
{
    person::obtain();
    cout << "Title: " << endl;
    getline (cin, title);
    getline (cin, title);
}

void manager::display()
{
    person::display();
    cout << "Title: " << title << endl;
}

Я был бы очень признателен, если бы кто-нибудь мог помочь мне понять, почему это происходит.


person ardunn    schedule 07.08.2014    source источник
comment
Не могли бы вы упростить код? Пока что это довольно долго.   -  person Karol S    schedule 07.08.2014
comment
Хм, я не уверен, как бы упростить это, но я думаю, что проблема в main()?   -  person ardunn    schedule 07.08.2014
comment
Как сделать меньший пример. Это ТОННА кода, который нужно пройти.   -  person Adam    schedule 07.08.2014
comment
Скомпилируйте все предупреждения и отладочную информацию (например, g++ -Wall -g при использовании GCC ....) и узнайте, как < b>используйте отладчик (например, gdb в Linux).   -  person Basile Starynkevitch    schedule 07.08.2014
comment
никаких предупреждений и ошибок...   -  person ardunn    schedule 07.08.2014
comment
Я был бы очень признателен, если бы вы могли разделить это на отдельные файлы. Обычно у меня есть заголовок и исходный файл для каждого класса.   -  person Thomas Matthews    schedule 07.08.2014


Ответы (2)


1) Нет необходимости в точке с запятой в конце вашего первого цикла for.

2) Если ввод пропускается, скорее всего, у вас есть мусор во входном буфере, который читается. Попробуйте это перед вторым циклом:

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

Смотрите эту ссылку: Мой cin игнорируется внутри цикла while< /а>

person PaulMcKenzie    schedule 07.08.2014
comment
будет работать просто cin.ignore()? Я поставил это после моего первого цикла, и та же проблема остается - person ardunn; 07.08.2014
comment
Возможно, вам потребуется сбросить бит ошибки. Используйте std::cin.clear(); перед вторым циклом и перед вызовом ignore(). - person PaulMcKenzie; 07.08.2014

cin >> decision; читает только до \n или пробела, как только он выводит вашу строку из входного буфера, \n все еще остается. Итак, на второй итерации, когда вы снова доберетесь до cin >> decision;, он читает до \n и завершает работу. Вам нужно очистить буфер, вызвав getline, чтобы использовать оставшееся \n.

person Fsmv    schedule 07.08.2014
comment
Опереди меня :) Как раз это печатал. - person Adam; 07.08.2014
comment
большое спасибо! так что я просто использую cin.getline(), чтобы получить решение? - person ardunn; 07.08.2014
comment
@user3919624 нет. getline(cin, decision); поможет. - person scohe001; 07.08.2014
comment
@ Джош, я должен сделать это и для первой итерации? - person ardunn; 07.08.2014
comment
теперь я получаю сообщение об ошибке: «ОШИБКА: нет соответствующего вызова функции для getline (std:: istream &, int &) - person ardunn; 07.08.2014
comment
Предполагается, что это char * во втором аргументе, вам нужна временная строковая переменная для хранения результата. - person Fsmv; 07.08.2014
comment
и тогда мне нужно преобразовать его? - person ardunn; 07.08.2014
comment
Нет вызова getline после того, как вы прочитали инт. как cin >> decision; char throwaway[2]; getline(cin, throwaway);, я сделал размер два, потому что ему нужно место для новой строки и нулевого терминатора. - person Fsmv; 07.08.2014
comment
нет функции для getline(cin, char[2])? это дает мне ошибку «ошибка: нет соответствующей функции для вызова getline (istream &, char [2])» - person ardunn; 07.08.2014
comment
О, извините, я запутался с другим вопросом и подумал, что вы по какой-то причине используете C. Используйте std::string вместо массива символов - person Fsmv; 07.08.2014