Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
the program works fine and executes all options, but in the 3rd and 4th option, in 3rd when i search for a student the program doesn't go beyond the data input part while in 4th when i search for data and print it, it gives garbage values in the variables with int datatype while doesn't display string or char type variables. any help would be much appreciated. EDIT: sorry for the inconvenience, I've now separated the functions form the main code. Hope its its more understandable now.
#include<iostream>
#include<string>
using namespace std;
int ncr;
int me,n=0,u,y,l;
char opt1,opt2,opt3,opt4;
struct student
{
string Name;
int DoB;
int Age;
string Address;
string Course[5];
char grade[5];
};
void add();
void remove();
void update();
void search();
int main()
{ int opt;
student s[n];
while(1)
{
cout<<" select what you want to do \n\n 1. Add new record \n2. Remove record\n3. Update Record\n4. Search for particular student\n" ;
cin>>opt;
if(opt==1)
{add();}
else if(opt==2)
{remove();}
else if(opt==3)
{update();}
else if(opt==4)
{search();}
}
}
.
void add(){
n++;
student s[n];
do
{ cout<<"enter name of student ";
cin>>s[n-1].Name;
cout<<"enter DoB of student ";
cin>>s[n-1].DoB;
cout<<"enter age of student ";
cin>>s[n-1].Age;
cout<<"enter address of student ";
cin>>s[n-1].Address;
cout<<"enter courses and grades (max 5) \n";
for(int x=0;x<5;x++){
cout<<"course:";
cin>>s[n-1].Course[x];
cout<<"grade:";
cin>> s[n-1].grade[x];}
cout<<"Roll No. : "<<n<<"\nName :"<<s[n-1].Name<<"\nDoB :"<<s[n-1].DoB<<"\nAge :"<<s[n-1].Age<<"\nAddress :"<<s[n-1].Address;
for(int x=0;x<5;x++){
cout<<"\n"<<s[n-1].Course[x];
cout<<" grade : "<< s[n-1].grade[x]<<"\n";}
cout<<"repeat for another student 'y' or 'n' ?";
cin>>opt1;
}
while(opt1=='y'|| opt1=='Y');
}
.
void remove(){student s[n];
do
{
cout<<"enter student roll no to remove data";cin>>l;
for(int i=l;i<n;i++)
{ s[l-1].Name=s[l].Name;
s[l-1].DoB= s[l].DoB;
s[l-1].Age=s[l].Age;
s[l-1].Address=s[l].Address;
for(int j=0;j<5;j++){
s[l-1].Course[j]=s[l].Course[j];
s[l-1].grade[j]=s[l].grade[j];}
}
cout<<"Record Removed\n";
n--;
cout<<"repeat ? 'y' or 'n' ";
cin>>opt2;
}
while(opt2 == 'y' || opt2 == 'Y');}
.
void update(){
student s[n];
do
{
cout<<"enter the roll no of student you want to update data";
cin>>u;
cout<<"Roll No. : "<<u;
cout<<"\nName : ";
cout<<s[u-1].Name;
cout<<"\nDoB : ";
cout<<s[u-1].DoB;
cout<<"\nAge : ";
cout<<s[u-1].Age;
cout<<"\nAddress :";
cout<<s[u-1].Address;
cout<<"\nCourses and Grades\n";
for(int r=0;r<5;r++)
{
cout<<s[u-1].Course[r];
cout<<"\t"<< s[u-1].grade[r]<<endl;
}
cout<<"enter name of student ";
cin>>s[u-1].Name;
cout<<"enter DoB of student ";
cin>>s[u-1].DoB;
cout<<"enter age of student ";
cin>>s[u-1].Age;
cout<<"enter address of student ";
cin>>s[u-1].Address;
cout<<"enter courses and grades (max 5) \n";
for(int x=0;x<5;x++){
cout<<"course:";
cin>>s[u-1].Course[x];
cout<<"grade:";
cin>> s[u-1].grade[x];}
cout<<"Roll No. : "<<u;
cout<<"\nName : ";
cout<<s[u-1].Name;
cout<<"\nDoB : ";
cout<<s[u-1].DoB;
cout<<"\nAge : ";
cout<<s[u-1].Age;
cout<<"\nAddress :";
cout<<s[u-1].Address;
cout<<"\nCourses and Grades\n";
for(int r=0;r<5;r++)
{ cout<<s[u-1].Course[r];
cout<<"\t"<< s[u-1].grade[r]<<endl; }
cout<<"repeat ? 'y' or 'n' ";
cin>>opt3;
}
while(opt3 == 'y' || opt3 == 'Y');
}
.
void search(){
student s[n];
do
{
cout<<"enter the roll no of student you want to search data of";
cin>>y;
cout<<"Roll No. : "<<n<<"\nName :"<<s[y-1].Name<<"\nDoB :"<<s[y-1].DoB<<"\nAge :"<<s[y-1].Age<<"\nAddress :"<<s[y-1].Address<<"\nCourses and Grades\n";
for(int r=0;r<5;r++)
{
cout<<s[y-1].Course[r];
cout<<"\t"<< s[y-1].grade[r]<<endl;
}
cout<<"repeat ? 'y' or 'n' ";
cin>>opt4;
}
while(opt4 == 'y' || opt4 == 'Y');}
This should look a bit more like a code intended for humans to read :)
#include<iostream>
#include<string>
using namespace std;
int ncr;
int me,n=0,u,y,l;
char opt1,opt2,opt3,opt4;
struct student
{
string Name;
int DoB;
int Age;
string Address;
string Course[5];
char grade[5];
};
void add();
void remove();
void update();
void search();
int main()
{
int opt;
student s[n];
while(1)
{
cout << " select what you want to do \n\n 1. Add new record \n2. Remove record\n3. Update Record\n4. Search for particular student\n" ;
cin >> opt;
if(opt==1)
{
add();
}
else if(opt==2)
{
remove();
}
else if(opt==3)
{
update();
}
else if(opt==4)
{
search();
}
}
}
void add()
{
n++;
student s[n];
do
{
cout << "enter name of student ";
cin >> s[n-1].Name;
cout << "enter DoB of student ";
cin >> s[n-1].DoB;
cout << "enter age of student ";
cin >> s[n-1].Age;
cout << "enter address of student ";
cin >> s[n-1].Address;
cout << "enter courses and grades (max 5) \n";
for(int x=0;x<5;x++)
{
cout<<"course:";
cin>>s[n-1].Course[x];
cout<<"grade:";
cin>> s[n-1].grade[x];
}
cout << "Roll No. : " << n << "\nName :" << s[n-1].Name << "\nDoB :" << s[n-1].DoB << "\nAge :" << s[n-1].Age << "\nAddress :" << s[n-1].Address;
for( int x = 0; x < 5; x++ )
{
cout << "\n"<<s[n-1].Course[x];
cout << " grade : "<< s[n-1].grade[x]<<"\n";}
cout << "repeat for another student 'y' or 'n' ?";
cin >> opt1;
}
while(opt1=='y'|| opt1=='Y');
}
void remove()
{
student s[n];
do
{
cout << "enter student roll no to remove data";
cin >> l;
for( int i=l; i < n; i++ )
{
s[l-1].Name=s[l].Name;
s[l-1].DoB= s[l].DoB;
s[l-1].Age=s[l].Age;
s[l-1].Address=s[l].Address;
for(int j=0;j<5;j++)
{
s[l-1].Course[j]=s[l].Course[j];
s[l-1].grade[j]=s[l].grade[j];
}
}
cout<<"Record Removed\n";
n--;
cout << "repeat ? 'y' or 'n' ";
cin >> opt2;
}
while(opt2 == 'y' || opt2 == 'Y');
}
void update()
{
student s[n];
do
{
cout << "enter the roll no of student you want to update data";
cin >> u;
cout << "Roll No. : " << u;
cout << "\nName : ";
cout << s[u-1].Name;
cout << "\nDoB : ";
cout << s[u-1].DoB;
cout << "\nAge : ";
cout << s[u-1].Age;
cout << "\nAddress :";
cout << s[u-1].Address;
cout << "\nCourses and Grades\n";
for( int r=0; r < 5; r++ )
{
cout << s[u-1].Course[r];
cout << "\t"<< s[u-1].grade[r] << endl;
}
cout << "enter name of student ";
cin >> s[u-1].Name;
cout << "enter DoB of student ";
cin >> s[u-1].DoB;
cout << "enter age of student ";
cin >> s[u-1].Age;
cout << "enter address of student ";
cin >> s[u-1].Address;
cout << "enter courses and grades (max 5) \n";
for(int x=0; x < 5; x++ )
{
cout<<"course:";
cin>>s[u-1].Course[x];
cout<<"grade:";
cin>> s[u-1].grade[x];
}
cout << "Roll No. : " << u;
cout << "\nName : ";
cout << s[u-1].Name;
cout << "\nDoB : ";
cout << s[u-1].DoB;
cout << "\nAge : ";
cout << s[u-1].Age;
cout << "\nAddress :";
cout << s[u-1].Address;
cout << "\nCourses and Grades\n";
for( int r = 0; r < 5; r++)
{
cout << s[u-1].Course[r];
cout << "\t"<< s[u-1].grade[r]<<endl;
}
cout << "repeat ? 'y' or 'n' ";
cin >> opt3;
}
while(opt3 == 'y' || opt3 == 'Y');
}
void search()
{
student s[n];
do
{
cout << "enter the roll no of student you want to search data of";
cin >> y;
cout << "Roll No. : " << n << "\nName :" << s[y-1].Name << "\nDoB :" << s[y-1].DoB << "\nAge :" << s[y-1].Age << "\nAddress :" << s[y-1].Address << "\nCourses and Grades\n";
for( int r=0; r < 5; r++ )
{
cout << s[y-1].Course[r];
cout << "\t" << s[y-1].grade[r]<<endl;
}
cout << "repeat ? 'y' or 'n' ";
cin >> opt4;
}
while( opt4 == 'y' || opt4 == 'Y' );
}
The problem you're having is with the scope of your programme.
In the main() function you declare an array, which presumably should be holding all the records. However for every option (function add/remove/update/search) you declare a new one. These arrays are local to those functions and are being "forgotten" after the function is finished.
In order to fix that, you have to pass the original array (the one from main()) to those functions.
The next problem, which is more severe is the fact, that you can't change the size of an array in the runtime! The elements you were accessing in the 3rd option were some random bytes in the memory and this can cause a lot of trouble.
Either create an array with e.g. 100 fields ( student s[100]; ), or even better try using std::vector, which can size you can adjust according to the number of records.
Third thing, remember that formatting code is extremely important. Hopefully it was just a copy-paste problem that made your code look unreadable, but if it's not the case then try to change. Well formatted code is easier to understand and will make it easier for you to debug it.
Related
I have the following code
for (int i = 0; i < courses; i++)
{
cout << "Please Enter Letter Grade: ";
cin >> grade1;
cout << "Please Enter Course Weighting: ";
cin >> weight1;
}
Now, lets say the loop runs 3 times and the values entered by the user for grade1 and weight1 are different each time. I want to store these different values so I can do some calculations with them. How would I proceed to do so?
Here is how use an array:
int grade[courses]; // this is an array with size of courses
double weight[courses];
for (int i = 0; i < courses; i++) {
cout << "Please Enter Letter Grade: ";
cin >> grade[i];
cout << "Please Enter Course Weighting: ";
cin >> weight[i];
}
Array is collection of data of the same type stored sequentially in computer memory. Syntax for array is as follow:
<type> <name>[<size>];
for example
int numberOfStudents[100];
is int array with maximum of 100 elements.
Hope This Helps
group grade and weight into a struct and store them in a vector.
code: (doesnt handle all potential errors)
#include <iostream>
#include <vector>
struct grade_weight
{
int grade;
int weight;
};
int main()
{
int courses = 5;
std::vector<grade_weight> result;
// potential optimization if you want
//result.reserve(courses);
for (int i = 0; i < courses; i++)
{
int grade, weight;
std::cout << "Please Enter Letter Grade: ";
std::cin >> grade;
std::cout << "Please Enter Course Weighting: ";
std::cin >> weight;
result.push_back({grade, weight});
}
std::cout << "you input\n";
for(auto& gw: result)
{
std::cout << "grade: " << gw.grade << ", weight: " << gw.weight << '\n';
}
}
I am supposed to write a program with two classes, Employee and Department. When the main() function runs, it asks the user to choose one of the six numbered options that are displayed and creates arrays for Employee and Department objects. I'm disregarding every other option except option 1, the Create Department Option, so the focus of this issue will be the Department class and the Department department[3] array.
There is a while loop in the main() function that continuously runs until the user decides to exit. If the user enters option 1, a Department array object is created, and then the user also enters the departmentID, departmentName, and departmentHeadName for that object. The while loop notifies the user if the array has three Employee objects. However, I am having difficulties because each departmentID needs to be unique. For example, I cannot enter 1 for the first array object's departmentID, and then enter 1 again for the second array object's departmentID. How do I check if the user's departmentID input already exists in a previous object?
#include <iostream>
#include <string>
using namespace std;
// Employee Class
class Employee
{
private:
string employeeID;
string employeeName;
string employeeDepartmentID;
double employeeSalary;
int employeeAge;
public:
void createEmployee()
{
cout << "Please Enter Employee Details:" << endl;
cout << "Employee ID : ";
cin >> employeeID;
cout << "Employee Name :";
cin >> employeeName;
cout << "Salary: $";
cin >> employeeSalary;
cout << "Age : ";
cin >> employeeAge;
cout << "Department ID : ";
cin >> employeeDepartmentID;
}
};
// Department Class
class Department
{
private:
string departmentID;
string departmentName;
string departmentHeadName;
public:
void createDepartment()
{
cout << "Please Enter Department Details: \n";
cout << "Department ID : ";
cin >> departmentID;
cout << "Department Name : ";
cin >> departmentName;
cout << "Head of Department : ";
cin >> departmentHeadName;
}
};
// Function prototype
void displayMenu();
// Client main function
int main()
{
Employee employee[5];
Department department[3];
int choice;
int departmentCount = 0;
int employeeCount = 0;
while (true)
{
displayMenu();
cin >> choice;
if (choice == 1 && departmentCount < 3)
{
department[departmentCount].createDepartment();
departmentCount = departmentCount + 1;
}
else if (choice == 1 && departmentCount >= 3)
{
cout << "\nThe array is full, you can not add any more Departments." << endl;
}
else if (choice == 2 && employeeCount < 5)
{
employee[employeeCount].createEmployee();
employeeCount = employeeCount + 1;
}
else if (choice == 2 && employeeCount >= 5)
{
cout << "The array is full, you can not add any more Employees." << endl;
}
else if (choice == 6)
{
cout << "Thank you, goodbye." << endl;
break;
}
}
return 0;
}
// Display menu function
void displayMenu()
{
cout << "1. Create Department" << endl;
cout << "2. Create Employee" << endl;
cout << "3. Write Out Data File" << endl;
cout << "4. Read In Data File" << endl;
cout << "5. Display Salary Report" << endl;
cout << "6. -- Quit -- " << endl;
cout << "Please make a selection : ";
}
try this one
#include <iostream>
#include <string>
using namespace std;
// Employee Class
class Employee
{
private:
string employeeID;
string employeeName;
string employeeDepartmentID;
double employeeSalary;
int employeeAge;
public:
void createEmployee()
{
cout << "Please Enter Employee Details:" << endl;
cout << "Employee ID : ";
cin >> employeeID;
cout << "Employee Name :";
cin >> employeeName;
cout << "Salary: $";
cin >> employeeSalary;
cout << "Age : ";
cin >> employeeAge;
cout << "Department ID : ";
cin >> employeeDepartmentID;
}
};
// Department Class
class Department
{
private:
string departmentID;
string departmentName;
string departmentHeadName;
public:
void createDepartment()
{
cout << "Please Enter Department Details: \n";
cout << "Department ID : ";
cin >> departmentID;
cout << "Department Name : ";
cin >> departmentName;
cout << "Head of Department : ";
cin >> departmentHeadName;
}
public:
string getDepartmentID(){
return departmentID;
}
};
// Function prototype
void displayMenu();
// Client main function
int main()
{
Employee employee[5];
Department department[3];
int choice;
int departmentCount = 0;
int employeeCount = 0;
while (true)
{
displayMenu();
cin >> choice;
if (choice == 1 && departmentCount < 3)
{
department[departmentCount].createDepartment();
for(int i=0;i<departmentCount;i++)
{
if(department[i].getDepartmentID()==department[departmentCount].getDepartmentID())
{
cout<<"already exists......................... \n";
}
}
departmentCount = departmentCount + 1;
}
else if (choice == 1 && departmentCount >= 3)
{
cout << "\nThe array is full, you can not add any more Departments." << endl;
}
else if (choice == 2 && employeeCount < 5)
{
employee[employeeCount].createEmployee();
employeeCount = employeeCount + 1;
}
else if (choice == 2 && employeeCount >= 5)
{
cout << "The array is full, you can not add any more Employees." << endl;
}
else if (choice == 6)
{
cout << "Thank you, goodbye." << endl;
break;
}
}
return 0;
}
// Display menu function
void displayMenu()
{
cout << "1. Create Department" << endl;
cout << "2. Create Employee" << endl;
cout << "3. Write Out Data File" << endl;
cout << "4. Read In Data File" << endl;
cout << "5. Display Salary Report" << endl;
cout << "6. -- Quit -- " << endl;
cout << "Please make a selection : ";
}
I used getDepartmentID function in Department Class to get department id from each department object
public:
string getDepartmentID(){
return departmentID;
}
there should be return type is string.because you have created departmentID as a string.
and I used For Loop in main function to compare relevant department id already exists or not
for(int i=0;i<departmentCount;i++)
{
if(department[i].getDepartmentID()==department[departmentCount].getDepartmentID())
{
cout<<"already exists......................... \n";
}
}
This question already has answers here:
Program not waiting for cin
(3 answers)
Closed 7 years ago.
I'm very new to C++ and for my assignment they want me to create a function that gets the users input which I've done here: (classList is an array)
public:
void userInput() {
string enterAgain;
do {
cout << "Enter the students name: " << name;
cin >> name;
cout << "Enter the number of classes the student is enrolled in: " << numClasses;
cin >> numClasses;
for (int i = 0; i < numClasses; i++) {
cout << "Enter the class list: " << (i+1) << classList;
cin >> classList;
i++;
}
cout << "Would you like to enter again (y for yes): " << enterAgain;
cin >> enterAgain;
} while (enterAgain == "Y" || enterAgain == "y");
}
When I run the program it will ask the user for the students name followed by the number of classes they're taking, but when it ask the user to input the class list it displays something like this:
Enter the class list: 0x7fff536d1b78
But in addition to this it won't let me input anything. I searched for hours trying to correct this problem and I was hoping someone could point me in the right direction in correcting this problem. Thanks!
public:
void userInput() {
string enterAgain;
do {
cout << "Enter the students name: " << name;
cin >> name;
cout << "Enter the number of classes the student is enrolled in: " << numClasses;
cin >> numClasses;
for (int i = 0; i < numClasses; i++) {
cout << "Enter the class list: " << (i+1) << classList;
cin >> classList;
i++;
}
cout << "Would you like to enter again (y for yes): " << enterAgain;
cin >> enterAgain;
} while (enterAgain == "Y" || enterAgain == "y");
}
should be-
public:
void userInput() {
string enterAgain;
do {
cout << "Enter the students name: " << endl;
cin >> name;
cout << "Enter the number of classes the student is enrolled in: " << endl;
cin >> numClasses;
for (int i = 0; i < numClasses; i++) {
cout << "Enter the class list: " << (i+1) << endl;
cin >> classList[i];
}
cout << "Would you like to enter again (y for yes): " << endl;
cin >> enterAgain;
} while (enterAgain == "Y" || enterAgain == "y");
}
I have this program in C++ for Student Management System , Everything is working fine , except one place where i try to delete a student based on his roll number .
What it should do : After asking the roll number search the record and delete it
What is it doing : It deletes all the other records which do not match that roll number
Here is my code :
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main() {
FILE *fp, *ft;
char another, choice;
struct student {
char first_name[50], last_name[50];
int roll_num; //new code added
char course[100];
int section;
};
struct student e;
char xfirst_name[50], xlast_name[50];
int xroll_num ; // new code added
long int recsize;
fp=fopen("users.txt","rb+");
if (fp == NULL) {
fp = fopen("users.txt","wb+");
if (fp==NULL)
{
puts("Cannot open file");
return 0;
}
}
recsize = sizeof(e);
while(1) {
system("cls");
cout << "\t\t====== STUDENT INFORMATION SYSTEM ======";
cout <<"\n\n ";
cout << "\n\n";
cout<<" \n\t\t\t======================";
cout << "\n \t\t\t 1. Add Records";
cout << "\n \t\t\t 2. List Records";
cout << "\n \t\t\t 3. Modify Records";
cout << "\n \t\t\t 4. Delete Records";
cout << "\n \t\t\t 5. Exit Program";
cout<<" \n\t\t\t======================";
cout << "\n\n";
cout << "\t\t\t Select Your Choice ::";
fflush(stdin);
choice = _getche();
switch(choice)
{
case '1' :
fseek(fp,0,SEEK_END);
another ='Y';
while(another == 'Y' || another == 'y')
{
system("cls");
cout << "Enter the First Name : ";
cin >> e.first_name;
cout << "Enter the Last Name : ";
cin >> e.last_name;
cout << "Enter the Course : ";
cin >> e.course;
cout << "Enter the Section : ";
cin >> e.section;
cout << "Enter the roll number :";
cin >> e.roll_num;
fwrite(&e,recsize,1,fp);
cout << "\n Add Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '2':
system("cls");
rewind(fp);
cout << "=== View the Records in the Database ===";
cout << "\n";
while (fread(&e,recsize,1,fp) == 1){
cout << "\n";
cout <<"\nName :: " <<e.first_name <<" "<<e.last_name;
//cout << "\n";
cout <<"\nRoll Number :: " << e.roll_num ;
cout <<"\nCourse :: " <<e.course ;
cout <<"\nSection :: "<<e.section;
}
cout << "\n\n";
system("pause");
break;
case '3' :
system("cls");
another = 'Y';
while (another == 'Y'|| another == 'y')
{
// cout << "\n Enter the last name of the student : ";
cout << "\n Enter the Roll number of the student : ";
cin >> xroll_num;
rewind(fp);
while (fread(&e,recsize,1,fp) == 1)
{
//if (strcmp(e.last_name,xlast_name) == 0)
if(e.roll_num == xroll_num )
{
cout << "Enter the new Firt Name : ";
cin >> e.first_name;
cout << "Enter the new Last Name : ";
cin >> e.last_name;
cout << "Enter the new Roll Number : ";
cin >> e.roll_num;
cout << "Enter the new Course : ";
cin >> e.course;
cout << "Enter the new Section : ";
cin >> e.section;
fseek(fp, - recsize, SEEK_CUR);
fwrite(&e,recsize,1,fp);
break;
}
else
cout<<"record not found";
}
cout << "\n Modify Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '4':
system("cls");
another = 'Y';
while (another == 'Y'|| another == 'y')
{
// cout << "\n Enter the last name of the student to delete : ";
cout <<"\n Enter the roll number of the student to delete : ";
cin >> xroll_num;
ft = fopen("temp.dat", "wb");
rewind(fp);
while (fread (&e, recsize,1,fp) == 1)
// if (strcmp(e.last_name,xlast_name) != 0)
if(e.roll_num == xroll_num )
{
fwrite(&e,recsize,1,ft);
}
fclose(fp);
fclose(ft);
remove("users.txt");
rename("temp.dat","users.txt");
fp=fopen("users.txt","rb+");
cout << "\n Delete Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '5':
fclose(fp);
cout << "\n\n";
cout << "\t\t THANK YOU FOR USING THIS SOFTWARE";
cout << "\n\n";
exit(0);
}
}
system("pause");
return 0;
}
It deletes all the other records which do not match that roll number
Well you're only writing the records that match the roll number to the temp file, and then using that file to overwrite the users.txt file
if (e.roll_num == xroll_num) {
fwrite(&e, recsize, 1, ft);
}
I suppose what you really wanted to do is
if (e.roll_num != xroll_num) {
fwrite(&e, recsize, 1, ft);
}
You should probably read a good C++ i/o tutorial, as your code is mostly C. Consider writing your student struct as simple text instead of writing it wholesale to the file.
So I have this do-while loop which is supposed to repeat asking if you want to enter info for a student if you do press y and enter info via an input() function the data is then stored in a vector. If you press q, the program is supposed to print the info contained in the vector and exit the loop.
For some reason the loop fully executes for the first and second student you enter. Then instead of repeating the loop asking if you want to enter a third student it seems to just execute the input() function. It doesn't ask you 'Enter y to continue or q to quit' and any student info you enter here does not seemed to be stored. It does this intermittently changing between executing the full loop and just the input() function. I'm wondering if anyone knows why this is happening and what I can do to fix it.
Cheers
#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;
}
I think this code does it:
n++;
for(size_t i=0; i<n; ++i)
{
s = input();
vec.push_back(s);
}
It asks you for two students the second time, for three student the third time, etc.
So, make it
vec.push_back(input());