调用for函数,只返回0
Calling for function, only returning 0
好了,我现在要做的目标是调用函数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;
};
相关文章:
- 为什么我的程序在for循环中k=0时返回垃圾值
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 有没有办法将 for 循环结果返回到像三元运算符这样的函数中?
- 从 for 循环返回每个值 in C++
- 基于范围的 for 循环,用于包含C++中的指针的自定义链表,仅返回对象
- 如果任何条件是错误的,如何从for循环中返回false
- 在for循环中增加结构值每次返回相同的值
- C++函数模板:必须使用 & for 参数类型和返回类型?
- 对简单的帐户检查程序有问题?程序返回编译错误,指出"no match for 'operator||' unsure of how to fix?"
- 编译错误:返回引用时"no matching function for call to" static_cast
- 为什么std :: iS_array返回false for sTD ::数组
- C 是否有办法仅返回for循环的最后一个实例
- 当循环返回"for each"项的 nullptr 时?
- C++For循环多次返回匹配的值
- 为什么 for(cont=100; cont>=20; cont-=10) 只返回一个值而不是一个系列
- ostream 重载与 for 循环,无返回值
- sqlite3_prepare_v2 返回 null for 语句
- 方法返回用于基于范围的for循环的容器
- 为什么 for(int i=0; i<10; ++i) 和 for(int i=0; i<10; i++) 返回相同的结果?
- 当从带有for循环的函数返回时检查对象是否存在