所以我有这个do-while循环,它应该重复询问你是否要为学生输入信息,如果你按y并通过input()函数输入info,则数据存储在向量中。如果按q,程序应该打印向量中包含的信息并退出循环。
由于某种原因,循环完全为您输入的第一个和第二个学生执行。然后,而不是重复循环询问您是否要进入第三个学生,它似乎只是执行input()函数。它不会问你'输入y继续或q退出',你输入的任何学生信息似乎都没有存储。它在执行完整循环和输入()函数之间间歇性地改变。我想知道是否有人知道为什么会这样,以及我可以做些什么来解决它。
干杯
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
const int NO_OF_TEST = 4;
struct studentType
{
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
};
studentType input();
double calculate_avg(int marks[],int NO_OF_TEST); // returns the average mark
string calculate_grade (double avgMark); // returns the grade
void main()
{
unsigned int n=0; // no. of student
vector<studentType> vec; // vector to store student info
studentType s;
char response;
do
{
cout << "\nEnter y to continue or q to quit... ";
cin >> response;
if (response == 'y')
{
n++;
for(size_t i=0; i<n; ++i)
{
s = input();
vec.push_back(s);
}
}
else if (response == 'q')
{
for (unsigned int y=0; y<n; y++)
{
cout << "\nFirst name: " << vec[y].firstName;
cout << "\nLast name: " << vec[y].lastName;
cout << "\nStudent ID: " << vec[y].studentID;
cout << "\nSubject name: " << vec[y].subjectName;
cout << "\nAverage mark: " << vec[y].avgMarks;
cout << "\nCourse grade: " << vec[y].courseGrade << endl << endl;
}
}
}
while(response!='q');
}
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 x=0; x<NO_OF_TEST; x++)
{ cout << "\nTest " << x+1 << " mark: ";
cin >> newStudent.arrayMarks[x];
}
newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST );
newStudent.courseGrade = calculate_grade (newStudent.avgMarks);
return newStudent;
}
double calculate_avg(int marks[], int NO_OF_TEST)
{
double sum=0;
for( int i=0; i<NO_OF_TEST; i++)
{
sum = sum+ marks[i];
}
return sum/NO_OF_TEST;
}
string calculate_grade (double avgMark)
{
string grade= "";
if (avgMark<50)
{
grade = "Fail";
}
else if (avgMark<65)
{
grade = "Pass";
}
else if (avgMark<75)
{
grade = "Credit";
}
else if (avgMark<85)
{
grade = "Distinction";
}
else
{
grade = "High Distinction";
}
return grade;
}
答案 0 :(得分:0)
我认为这段代码可以做到:
n++;
for(size_t i=0; i<n; ++i)
{
s = input();
vec.push_back(s);
}
第二次询问你们两个学生,第三次是三个学生,等等。
所以,做吧
vec.push_back(input());