gpt4 book ai didi

c++ - 如何从 C++ 中的函数返回结构?

转载 作者:IT老高 更新时间:2023-10-28 12:59:11 25 4
gpt4 key购买 nike

我在几个不同的论坛上尝试过,似乎无法得到一个直接的答案,我怎样才能让这个函数返回结构?如果我尝试'return newStudent;'我收到错误消息“不存在从 studentType 到 studentType 的合适的用户定义转换。”

// Input function
studentType newStudent()
{
struct studentType
{
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;

int arrayMarks[4];

double avgMarks;

} newStudent;

cout << "\nPlease enter student information:\n";

cout << "\nFirst Name: ";
cin >> newStudent.firstName;

cout << "\nLast Name: ";
cin >> newStudent.lastName;

cout << "\nStudent ID: ";
cin >> newStudent.studentID;

cout << "\nSubject Name: ";
cin >> newStudent.subjectName;

for (int i = 0; i < NO_OF_TEST; i++)
{ cout << "\nTest " << i+1 << " mark: ";
cin >> newStudent.arrayMarks[i];
}

newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST );
newStudent.courseGrade = calculate_grade (newStudent.avgMarks);

}

最佳答案

这是您的代码的编辑版本,它基于 ISO C++ 并且与 G++ 配合良好:

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

#define NO_OF_TEST 1

struct studentType {
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
};

studentType input() {
studentType newStudent;
cout << "\nPlease enter student information:\n";

cout << "\nFirst Name: ";
cin >> newStudent.firstName;

cout << "\nLast Name: ";
cin >> newStudent.lastName;

cout << "\nStudent ID: ";
cin >> newStudent.studentID;

cout << "\nSubject Name: ";
cin >> newStudent.subjectName;

for (int i = 0; i < NO_OF_TEST; i++) {
cout << "\nTest " << i+1 << " mark: ";
cin >> newStudent.arrayMarks[i];
}

return newStudent;
}

int main() {
studentType s;
s = input();

cout <<"\n========"<< endl << "Collected the details of "
<< s.firstName << endl;

return 0;
}

关于c++ - 如何从 C++ 中的函数返回结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com