首页 > 解决方案 > 我确实需要一些帮助来创建一个显示信息的循环

问题描述

我正在尝试输出提供的所有信息,但我只能输出输入了一组时间的最终输出。我对循环很陌生

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

int sized = 0;

 //Global array declaration 
 Employee Array [60]:

//Struct declaration
struct Employee
{
    string name;
    int age;
    double salary;
};

//Protype
void Showinfo(Employee);

int main()
{
    //Declaring a variable of type Employee
    Employee Emp;

    cout << "Enter the number of employees you want to enter into the database: ";
    cin >> sized;
    cout << endl << endl;
    system("cls");

    //Getting the name of the Employee
    for (int i = 0; i < sized; i++)
    {
        cout << "Enter Full name of employee: ";
        cin.ignore();
        getline(cin, Emp.name);
        cout << endl;
        cout << "Enter age of employee: ";
        cin >> Emp.age;
        cout << endl;
        cout << "Enter salary of employee: ";
        cin >> Emp.salary;
        cout << endl;
        system("cls");
    }

    // To display the elements of the information given
    cout << endl << "Displaying Information." << endl;
    cout << "--------------------------------" << endl;

    for (int i = 0; i < sized; i++)
    {
        Showinfo(Emp);
    }

    cin.ignore();
    return 0;
}

//To display/showcase the information received
void Showinfo(Employee Emp)
{
    cout << "Name: " << Emp.name << endl;
    cout << "Age: " << Emp.age << endl;
    cout << "Salary: " << Emp.salary << endl << endl;
}

预期的结果就像

用户输入***

输入要存储的信息数量:2

输入姓名:球

输入年龄:69

输入工资:420

输入名称:拉力赛

输入年龄:42

输入工资:690000

预期输出:显示信息 ------------- 名称:球

年龄:69

工资:420

名称:拉力赛

年龄:42

工资:690000

我的输出显示信息

名称:拉力赛

年龄:42

工资:690000

名称:拉力赛

年龄:42

工资:690000

所以基本上我的程序输出接收到的最终信息集 * Sized number of times

标签: c++loopsvector

解决方案


所以基本上我的程序输出收到的最后一组信息

因为您只定义了一个实例Employee

Employee Emp;

然后将您的输入存储到该单个Emp.

你想要更多类似的东西:

cout << "Enter the number of employees you want to enter into the database: ";
cin >> sized;
//Declaring a vector type Employee of size sized
std::vector<Employee> Emps(sized);

推荐阅读