【问题标题】:C++ how can i loop the function in a class so that i can set more than one estudiante info?C ++我如何在一个类中循环函数,以便我可以设置多个学生信息?
【发布时间】:2021-11-03 05:21:24
【问题描述】:
#include <iostream>
#include <cmath>
#include <array>

using namespace std;

int x;

class estudiante
{
    private:
        string  nombre,cedula,codigo,direccion;

    public:
       void getDetalles(void);
       void setDetalles(void);
};

void estudiante::getDetalles(void){
    x=0;
    cout << "Ingrese el nombre del estudiante "<<x+1<<":" ;
    cin >> nombre;`
    cout << "Ingrese el numero de cedula: ";
    cin >> cedula;
    cout << "Ingrese el codigo: ";
    cin >> codigo;
    cout << "Ingrese la direccion ";
    cin >> direccion;

}

void estudiante::setDetalles(void){
    cout << "La informacion de estudiante "<<x+1<<": \n";
    cout << "Nombre:"<< nombre<<"\n";
    cout << "Cedula:"<< cedula<<"\n";
    cout << "Codigo:"<< codigo<<"\n";
    cout << "Direccion:"<< direccion<<"\n";

 }

int main()
{
     estudiante std;

    std.getDetalles();
    std.setDetalles();

   return 0;
}

这是我的代码,但我需要插入 3 组学生,然后它应该打印详细信息(detalles)

the input

the output

【问题讨论】:

标签: c++ class c++11


【解决方案1】:

您可以使用std::vector&lt;&gt; 来实现此目的。下面是工作示例。 3个学生一个一个。您可以将学生人数作为输入更改为您想要的值,甚至可以从用户那里获取。

#include <iostream>
#include <cmath>
#include <array>
#include <vector>
using namespace std;

int x;

class estudiante
{
    private:
        string  nombre,cedula,codigo,direccion;

    public:
       void getDetalles(void);
       void setDetalles(void);
};

void estudiante::getDetalles(void){
    x=0;
    cout << "Ingrese el nombre del estudiante "<<x+1<<":" ;
    cin >> nombre;
    cout << "Ingrese el numero de cedula: ";
    cin >> cedula;
    cout << "Ingrese el codigo: ";
    cin >> codigo;
    cout << "Ingrese la direccion ";
    cin >> direccion;

}

void estudiante::setDetalles(void){
    cout << "La informacion de estudiante "<<x+1<<": \n";
    cout << "Nombre:"<< nombre<<"\n";
    cout << "Cedula:"<< cedula<<"\n";
    cout << "Codigo:"<< codigo<<"\n";
    cout << "Direccion:"<< direccion<<"\n";

 }

int main()
{
    std::vector<estudiante> studentList;//a vector of students 
    //this is the input loop
    for(int i = 0; i < 3; ++i)//this loop will create 3 students and push them onto the vector above. You can change the value 3
    {
       estudiante temporarysStdnt;

       temporarysStdnt.getDetalles();
      // temporarysStdnt.setDetalles(); 
       
       studentList.push_back(temporarysStdnt);
    }
    
    //now to output the details of all the students
    for(estudiante& Student: studentList)
    {
        Student.setDetalles();
    }
   return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2023-04-03
    • 2022-07-22
    相关资源
    最近更新 更多