Вызов функции, которая заполняет массив в моей главной не работает - PullRequest
0 голосов
/ 08 мая 2019

Мне нужно создать функции, а затем использовать их и вызывать их в main. Функция не вызывается, так в чем моя ошибка?

Когда код был в main, он работал отлично и без помех, но когда я взял его из main и поместил в функцию, он больше не работал, и я думаю, что функция вызывается неправильно.

#include <iostream>
#include <string>
#include <array>
using namespace std;

void fillEmployees(string names[50], int salaries[50][4], int N) {

    for (int i = 1; i <= N; i++) {
        cout << "Please enter the name and salaries of employee " << i << " throughout the four quarters: ";
        cin >> names[i];
        for (int quarters = 0; quarters < 4; quarters++)
            cin >> salaries[N][quarters];
    }
}

int main() {

    string nameOfCompany;
    int N;

    cout << "Enter the name of the company and its number of employees: ";
    cin >> nameOfCompany >> N;

    void fillEmployees(string names[50], int salaries[50][4], int N);

    system("pause");
    return 0;
}

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

1 Ответ

0 голосов
/ 08 мая 2019

Мы, новички, должны помогать друг другу. :)

В вашей программе много ошибок.

Для начала заголовок <array> избыточен в вашей программе, потому что не используется ни одно объявление из заголовка.

Вы не должны использовать магические числа (50 и 4), как в объявлении функции

void fillEmployees(string names[50], int salaries[50][4], int N) {

Индексы массивов (и стандартных контейнеров) начинаются с 0.

Функция fillEmployees не вызывается в программе.

Это объявление функции в main, а не ее вызов

void fillEmployees(string names[50], int salaries[50][4], int N);

Вы должны объявить контейнер, в котором вы будете хранить информацию о сотрудниках.

Я мог бы предложить следующее решение.

#include <iostream>
#include <string>
#include <utility>
#include <array>
#include <vector>

const size_t MAX_NUMBER_OF_EMPLOYEES = 50;
const size_t NUMBER_OF_QUATERS = 4;

using CompanyStuff = std::vector<std::pair<std::string, std::array<int, NUMBER_OF_QUATERS>>>;

void fillEmployees( CompanyStuff &employees )
{
    for ( CompanyStuff::size_type i = 0; i < employees.size(); i++ )
    {
        std::cout << "Please enter the name of the employee #" << i + 1 << ": ";
        std::getline( std::cin, employees[i].first );

        std::cout << "and his salaries throughout the " << NUMBER_OF_QUATERS << " quarters: ";
        for ( int &salary : employees[i].second ) std::cin >> salary;

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

std::ostream & displayCompanyStuff( const std::string &nameOfCompany, const CompanyStuff &employees, std::ostream &os = std::cout )
{
    os << "\nThe company name: " << nameOfCompany << '\n';
    os << "Employees:\n";

    for ( const auto &employee : employees )
    {
        os << '\t' << employee.first << ": ";
        for ( const auto &salary : employee.second ) os << salary << ' ';
        os << '\n';
    }

    return os;
}

int main()
{
    std::string nameOfCompany; 
    size_t numberOfEmployees;

    std::cout << "Enter the name of the company and its number of employees: ";

    if ( not std::getline( std::cin, nameOfCompany ) ) 
    {
        nameOfCompany = "Unknown";
    }

    if ( not ( std::cin >> numberOfEmployees ) or ( MAX_NUMBER_OF_EMPLOYEES < numberOfEmployees ) ) 
    {
        numberOfEmployees = MAX_NUMBER_OF_EMPLOYEES;
    }        

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


    CompanyStuff employees( numberOfEmployees );

    fillEmployees( employees );

    displayCompanyStuff( nameOfCompany, employees );
}

Вывод программы может выглядеть следующим образом

Enter the name of the company and its number of employees: The bset company
2
Please enter the name of the employee #1: Peter
and his salaries throughout the 4 quarters: 3500 3500 3500 3500
Please enter the name of the employee #2: Bob
and his salaries throughout the 4 quarters: 4000 4000 4000 4000

The company name: The best company
Employees:
    Peter: 3500 3500 3500 3500 
    Bob: 4000 4000 4000 4000 
...