调用for函数,只返回0

Calling for function, only returning 0

本文关键字:返回 for 函数 调用      更新时间:2023-10-16

好了,我现在要做的目标是调用函数getSingleStudentInfo,它包含学生的号码、姓氏和年龄。最后,这个程序被设计成做两件事,第一件是单个学生信息,第二件是打印一个包含20个学生的数组。忽略第二部分,因为我还没有真正讨论这部分,所以忽略任何涉及向量的内容。

我遇到的问题是,该程序将做的第一件事是要求您按1表示单个信息,或按2表示完整的20人信息。程序编译得很好,但是发生的事情是,无论你输入什么数字,程序都会说"进程返回0 (0x0)",然后完成,我很难弄清楚为什么它会这样做,而不是打印出单个学生信息,"学生的ID号是400"学生的姓是:Simmons"学生的年龄是:20"

#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Student {
    int studentNumber = 400;
    string lastName = "Simmons";
    int age = 20;
};
Student s;
int selection;
vector<int> studentNumber (20);
vector<string> lastName;
vector<int> age (20);
void getSingleStudentInfo (int studentNumber, string lastName, int age) {
    cout << "Student's ID number is: ";
    cout << s.studentNumber << endl;
    cout << "Student's last name is: ";
    cout << s.lastName << endl;
    cout << "Student's age is: ";
    cout << s.age << endl;
return;
};
int main()
{
    cout << "Press '1' to see a single student data entry" << endl;
    cout << "Press '2' to see all 20 student records" << endl;
    cin >> selection;
    if (selection == 1) {
    getSingleStudentInfo;
    };
    /*for (vector<int>::size_type i = 0; i <= 20; i++)
    {
        cout << "Student's ID number is: " << 400 + i << endl;
    }
    return 0;*/
}

您需要调用函数,例如

if (selection == 1)
{
    getSingleStudentInfo(7, "Johnson", 20);
}

然而,从实现上看,这应该是学生自身的一个方法

struct Student {
    int studentNumber = 400;
    string lastName = "Simmons";
    int age = 20;
    void getSingleStudentInfo() const;
};

那么你就把它称为Student实例

Student s{400, "Simmons", 20};
s.getSingleStudentInfo();

如果你有一个Student的向量你可以做

std::vector<Student> students; // assume this has been populated
std::for_each(begin(students),
              end(students),
              [](const Student& s){s.getSingleStudentInfo();});

要按列打印,可以将函数更改为

void Student::getSingleStudentInfo()
{
    cout << s.studentNumber << 't'
         << s.lastName << 't'
         << s.age << endl;
};