this code should record school data names and address but after input it repeats "enter names of teachers:" line several times before the output of data entered successfully how can i fix this problem? any tweaks in the code to achieve this? it should be school projects in C++ but I can't fix this problem at all I would apprecciate any help
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string sname, saddress, sname_teacher;
int snumber_classrooms;
double ratio, snumber_students, snumber_teachers;
//Entering data of school
cout << "Enter school data: \n";
cout << "Enter name of school : ";
cin >> sname;
cout << "Enter an address of school : ";
cin >> saddress;
cout << "Enter number of classrooms of the school : ";
cin >> snumber_classrooms;
cout << "Enter number of students of the school : ";
cin >> snumber_students;
cout << "Enter number of teachers of the school : ";
cin >> snumber_teachers;
//check if number of teachers < 20 or not
if (snumber_teachers > 20) {
while (snumber_teachers > 20) {
cout << " The number of teachers should not be more than 20 teachers. \n";
cout << "Enter number of teachers of the school : ";
cin >> snumber_teachers;
}
}
//check if number of teachers : number of students < (1/50=0.02)
ratio = snumber_teachers / snumber_students;
while (ratio < 0.02) {
cout << " The number of teachers should not be less than 1/50 number of students. \n";
cout << "Enter number of teachers of the school : ";
cin >> snumber_teachers;
ratio = snumber_teachers / snumber_students;
}
// Entering names of teachers
int snumber_teachers2 = snumber_teachers;
stack<string> names;
for (int i = 0; i < snumber_teachers2; i++) {
cout << "Enter names of teachers : ";
cin >> sname_teacher;
names.push(sname_teacher);
}
cout << " \n The Data of shool has entered succedly :)\n \n";
// Printing data of school
cout << " _______________________The Data of school are_______________________ \n";
cout << " name : " + sname << endl;
cout << " address " + saddress << endl;
cout << " classrooms : " << snumber_classrooms << endl;
cout << " students : " << snumber_students << endl;
cout << " teachers : " << snumber_teachers << endl;
cout << " names of teachers : \n";
// Printing content of stack
while (!names.empty()) {
cout << ' ' << names.top();
names.pop();
cout << "\n";
}
return 0;
}
You want to receive several inputs for teacher names, but only prompt "Enter names of teachers : " once.
So change
for (int i = 0; i < snumber_teachers2; i++) {
cout << "Enter names of teachers : ";
cin >> sname_teacher;
names.push(sname_teacher);
}
to
cout << "Enter names of teachers : ";
for (int i = 0; i < snumber_teachers2; i++) {
cin >> sname_teacher;
names.push(sname_teacher);
}
I.e. keep what you want to repeat inside the loop,
but move what you only want once outside.
Related
So I am trying to create a ATM system that lets user to input value such as Account number, account name and amount. But I can't figure out what exactly I have to do
int AccNum[2];
string AccName[2];
float AccBal[2];
cout << "********** ENTER ACCOUNT **********"<<endl;
for(int num = 0; num < 2; num++){
cout << "Enter Account number: ";
cin >> AccNum[num];
for(int name = num; name < 2; name++){
cout << "Enter Account Name: ";
getline(cin, AccName[name]);
for(int bal = name; bal < 2; bal++){
cout << "Enter Amount: ";
cin >> AccBal[bal];
}
}
}
I have tried something like this but it does not give the result that I want. The ideal result would be
********** ENTER ACCOUNT **********
Enter Account number: 1231232
Enter Account name: James white
Enter amount: 1000
it will run 2 times so there would be 2 accounts after this loop that will have a result like this
********** THE ACCOUNT IS **********
Account number: 1231232
Account name: James white
Balance: 1000
So the code you wrote is nearly good. Too many loops in my opinion
int AccNum[2];
string AccName[2];
float AccBal[2];
cout << "********** ENTER ACCOUNT **********"<<endl;
for(int num = 0; num < 2; num++){ // lets call this loop a. happens 2 times
cout << "Enter Account number: ";
cin >> AccNum[num];
for(int name = num; name < 2; name++){ // loop b happens 2 times * loop a times
cout << "Enter Account Name: ";
getline(cin, AccName[name]);
for(int bal = name; bal < 2; bal++){ loop c = 2 * a * b = 8
cout << "Enter Amount: ";
cin >> AccBal[bal];
}
}
}
Direct fix:
int main()
{
int AccNum[2];
string AccName[2];
float AccBal[2];
cout << "********** ENTER ACCOUNT **********" << endl;
for(int num = 0; num < 2; num++){
cout << "Enter Account number: ";
cin >> AccNum[num];
cout << "Enter Account Name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, AccName[num]);
cout << "Enter Amount: ";
cin >> AccBal[num];
}
for(int i = 0; i < 2; i++)
cout << "********** ENTER ACCOUNT **********" << endl
<< "Account number: " << AccNum[i] << endl
<< "Account name: " << AccName[i] << endl
<< "Balance: " << AccBal[i] << endl << endl;
}
But if you want to expand it a little bit:
#include <iostream>
#include <vector>
using namespace std;
struct Account
{
int Number;
string Name;
float Balance;
Account(int num, string nam, float bal) : Number(num), Name(nam), Balance(bal) {}
Account() {}
void getData()
{
cout << "Enter Account number: ";
cin >> Number;
cout << "Enter Account Name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, Name);
cout << "Enter Amount: ";
cin >> Balance;
}
void printAccount()
{
cout << "********** ENTER ACCOUNT **********" << endl
<< "Account number: " << Number << endl
<< "Account name: " << Name << endl
<< "Balance: " << Balance << endl << endl;
}
};
int main()
{
vector<Account> accounts;
for(int i = 0; i < 2; i++)
{
Account person;
person.getData();
accounts.emplace_back(person);
}
for(int i = 0; i < 2; i++) accounts[i].printAccount();
}
Both codes give the exact same output:
I'm writing a code to enter subjects' information where I put void function and array as an object. But not sure when I wanna loop it, it doesn't come until the end. Have a look at the code.
void calculateCGPA::getGPA() {
cout << "Enter the the name of the subject: ";
cin >> subjectName;
cout << "Enter the credit hour:";
cin >> credithour;
cout << "Enter the grade: ";
cin >> grade;
}
int main () {
for (year=1; year<=4; year++) {
for (sem=1; sem<=2; sem++) {
cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
cin >> totalSubjectSem;
calculateCGPA ob[totalSubjectSem];
for(int i = 1; i <= totalSubjectSem; i++) {
cout << "Subject " << i << ": \n";
ob[i].getGPA();
}
}
}
return 0;
}
Here's the error. You can see the compiler only shows until entering the subject name but credit hour and grade are omitted. What should I do?
Expected: It should everything in void function until 3 (since I put 3) and then start over again "Enter total subject you take in Year 1 sem 2" but it also omits that
Take note that in C++ 0 is the first element, and n-1 is the last element. By looping to n, you cause a buffer overflow, hence resulting an error.
A solution would be as follows
void calculateCGPA::getGPA() {
cout << "Enter the the name of the subject: ";
cin >> subjectName;
cout << "Enter the credit hour:";
cin >> credithour;
cout << "Enter the grade: ";
cin >> grade;
}
int main () {
for (year=0; year<4; year++) {
for (sem=0; sem<2; sem++) {
cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
cin >> totalSubjectSem;
calculateCGPA ob[totalSubjectSem];
for(int i = 0; i < totalSubjectSem; i++) {
cout << "Subject " << i << ": \n";
ob[i].getGPA();
}
}
}
}
calculateCGPA ob[totalSubjectSem];
It's GCC extension called Variable-length automatic arrays and not valid C++ (because totalSubjectSem is not const). Use std::vector<calculateCGPA> instead.
for(int i = 1; i <= totalSubjectSem; i++) {
Indices start from 0 and going to array_length - 1. On last iteration you reading out of array bounds and program is crashing.
I am to create an application that takes at least 5 employees i.d, names, pay rate, and hours. And then I am to add the pay rate and the hours together to show the gross pay for each employee at the end of the initial inquiries. I am stuck on how to add it in the vector please help!
** Here is the assignment that our instructor gave us **
http://itweb.fvtc.edu/ag/?u=3&f=cpp-assignment4
I've added a vector and added all the essential information for the employee
#include <iostream>
#include <conio.h>
#include <string>
#include <vector>
using namespace std;
struct Employee
{
int id;
string firstName;
string lastName;
float payRate;
int hours;
};
int main()
{
/*========= other way of adding employee information ==========*/
/*const int NUM_EMPLOYEE = 5;
Employee employee[NUM_EMPLOYEE];
for (int i = 0; i < 5; i++)
{
cout << "ID of employee " << (i + 1) << ": ";
cin >> employee[i].id;
cout << "First Name of employee " << (i + 1) << ": ";
cin >> employee[i].firstName;
cout << "Last Name of employee " << (i + 1) << ": ";
cin >> employee[i].lastName;
cout << "Pay rate for employee " << (i + 1) << ": ";
cin >> employee[i].payRate;
cout << "Hours worked " << (i + 1) << ": ";
cin >> employee[i].hours;
}*/
/*========= End of other way of adding employee information ==========*/
vector<Employee> employees;
char Another = 'y';
while (Another == 'y' || Another == 'Y')
{
Employee e;
cout << "Enter employee ID: \n";
cin >> e.id;
cout << "Enter employee first name: \n";
cin >> e.firstName;
cout << "Enter employee last name: \n";
cin >> e.lastName;
cout << "Enter employee pay rate: \n";
cin >> e.payRate;
cout << "Enter employee hours worked: \n";
cin >> e.hours;
employees.push_back(e);
cout << "Another? (y/n): \n";
cin >> Another;
}
float sum = 0;
vector<Employee>::iterator it = employees.begin();
for (; it != employees.end(); it++)
{
cout << "ID of employee: \n" << it->id << ": \n"
<< "Employees name: \n" << it->firstName << " " << it->lastName << ": \n"
<< "Employee pay rate: \n" << it->payRate << ": \n"
<< "Employee hours worked: \n" << it->hours << "\n";
}
float avg = sum / employees.size();
Employee e;
/*cout << " ID of employees: \n" << e.id;
cout << " Name of employees: \n" << e.firstName << " " <<
e.lastName;*/
cout << "Gross pay of employees: \n" << avg;
_getch();
return 0;
}
Show Id, names, and gross pay of all employees to user
vector<Employee> employees;
char Another = 'y';
while (Another == 'y' || Another == 'Y')
{
Employee e;
cout << "Enter employee ID: \n";
cin >> e.id;
cout << "Enter employee first name: \n";
cin >> e.firstName;
cout << "Enter employee last name: \n";
cin >> e.lastName;
cout << "Enter employee pay rate: \n";
cin >> e.payRate;
cout << "Enter employee hours worked: \n";
cin >> e.hours;
employees.push_back(e);
cout << "Another? (y/n): \n";
cin >> Another;
}
float sum = 0;
vector<Employee>::iterator it = employees.begin();
cout << "ID" << "\t" << "First Name" << "\t" << "Last Name" << "\t" << "Pay rate" << "\t" << "Hours" << "\t" << "Gross Pay" << "\n" ;
for (; it != employees.end(); it++)
{
float grossPay = it->payRate * it->hours;
cout << it->id << "\t" << it->firstName << "\t\t" << it->lastName << "\t\t" << it->payRate << "\t\t"
<< it->hours << "$" << "\t" << grossPay << "\n";
sum += grossPay;
}
cout << "The gross pay for all employee is: " << "$" << sum;
_getch();
return 0;
}
//This is what i got so far. But if I want to make the application ask the user to input how many employee they want to enter into the database how do i do that? would it be like this?
int EMPLOYEE_NUM[][] // ??
Okay, so I am writing a C++ program to declare a struct data type that holds the following information on an employee (First Name, Last Name, ID, Pay Rate, and Hours). My problem is that the user can only enter in the ID and First Name, then the whole program runs without letting the user enter the rest of the data.
Heres my code:
#include <iostream>
#include <iomanip>
using namespace std;
struct Employee
{
int employeeID;
char firstName;
char lastName;
float payRate;
int hours;
};
int main()
{
int i, j;
cout << "How Many Employees Do You Wish To Enter?:\n\n";
cin >> j;
Employee info;
for (i = 0; i < j; i++)
{
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << setw(5) << "\n Please Enter The Employee ID Number: ";
cin >> info.employeeID;
cout << setw(5) << "\n Please Enter Employees First Name: ";
cin >> info.firstName;
cout << setw(5) << "\n Please Enter Employees Last Name: ";
cin >> info.lastName;
cout << setw(5) << "\n Please Enter Employees Pay Rate: ";
cin >> info.payRate;
cout << setw(5) << "\n Please Enter The Hours The Employee Worked:
";
cin >> info.hours;
}
cout << "\n\n \n";
cout << "ID" << setw(15) << "First Name" << setw(10) << "Last Name" <<
setw(10) << "Pay Rate" << setw(10) << "Hours";
cout << endl;
for (i = 0; i < j; i++)
{
cout << "\n" << info.employeeID << setw(15) << info.firstName << setw(10) << info.lastName << setw(10) << info.payRate << setw(10) << info.hours;
}
cout << "\n\n \n";
system("pause");
return 0;
};
#include <iostream>
#include <iomanip>
#include <string> //Allows you to use strings, which are way more handy for text manipulation
#include <vector> //Allows you to use vector which are meant to be rezied dynamicaly, which is your case
using namespace std;
struct Employee
{
int employeeID;
string firstName; //HERE : use string instead of char (string are array of char)
string lastName; //HERE : use string instead of char
float payRate;
int hours;
};
int main()
{
int j;
cout << "How Many Employees Do You Wish To Enter?:\n\n";
cin >> j;
vector<struct Employee> info; //creation of the vector (dynamic array) to store the employee info the user is going to give you
for (int i = 0; i < j; i++) //declare your looping iterator "i" here, you will avoid many error
{
struct Employee employee_i; // create an employee at each iteration to associate the current info
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << "\n Please Enter The Employee ID Number: ";
cin >> employee_i.employeeID;
cout << "\n Please Enter Employees First Name: ";
cin >> employee_i.firstName;
cout << "\n Please Enter Employees Last Name: ";
cin >> employee_i.lastName;
cout << "\n Please Enter Employees Pay Rate: ";
cin >> employee_i.payRate;
cout << "\n Please Enter The Hours The Employee Worked: ";
cin >> employee_i.hours;
info.push_back(employee_i); //store that employee info into your vector. Push_back() methods expands the vector size by 1 each time, to be able to put your item in it
} // because you employee variable was create IN the loop, he will be destruct here, but not the vector which was created outside
cout << "\n\n \n";
for (int i = 0; i < j; i++) //the loop to get back all the info from the vector
{
cout << "ID :" << info[i].employeeID << " First Name :" << info[i].firstName << " Last Name :" <<
info[i].lastName << " Pay Rate :" << info[i].payRate << " Hours :"<< info[i].hours;
cout << endl;
//notice the info[i], which leads you to the employee you need and the ".hours" which leads to the hours info of that specific employee
}
system("pause");
return 0;
}
First, please read Tips and tricks for using C++ I/O (input/output). It might be helpful to understand C++ I/O.
Here are some comments on your code:
First
Use string instead of char.
struct Employee
{
int employeeID;
string firstName;
string lastName;
float payRate;
int hours;
};
Second
Use array of Employee object to store multiple employees.
Employee info[100];
Third
Use cin carefully depending data types. In your case, it would be something like this:
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << setw(5) << "\n Please Enter The Employee ID Number: ";
cin >> info[i].employeeID;
cin.ignore(); //It is placed to ignore new line character.
cout << setw(5) << "\n Please Enter Employees First Name: ";
getline (cin, info[i].firstName);
cout << setw(5) << "\n Please Enter Employees Last Name: ";
getline (cin, info[i].lastName);
cout << setw(5) << "\n Please Enter Employees Pay Rate: ";
cin >> info[i].payRate;
cout << setw(5) << "\n Please Enter The Hours The Employee Worked: ";
cin >> info[i].hours;
Fourth
std::getline() can run into problems when used before std::cin >> var. So, std::cin.ignore() can be used in this case to solve the problem.
I hope it helps.
My issue is that I have set up an array to store totals that were calculated from values read from a file. These stored totals are then added together to find the over all average.
This issue is stemming from a 'cin' at the beginning of the program where the user inputs a number and that number is supposed to drive the program by setting how many times the program loops and how many modules are inside the array. The array does not seem to work properly no matter how much I try.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string StudentGrades;
int studentID;
double quiz1;
double quiz2;
double quiz3;
double quiz4;
int total = 0;
double choice;
ofstream outFile;
double numStud=1;
cout << "Enter student ID number, Quiz 1 Grade, Quiz 2 Grade , Quiz 3 Grade, Quiz 4 Grade" << endl;
outFile.open("StudentGrades.txt");
cout << "How many students would you like to enter?" << endl;
cin >> numStud;
for (int x = 0; x < numStud; x++)
{
cout << "Enter student ID: ";
cin >> studentID;
cout << "Enter quiz grade 1: ";
cin >> quiz1;
//cout << quiz1;
cout << "Enter quiz grade 2: ";
cin >> quiz2;
//cout << quiz2;
cout << "Enter quiz grade 3: ";
cin >> quiz3;
//cout << quiz3;
cout << "Enter quiz grade 4: ";
cin >> quiz4;
//cout << quiz4;
cout << endl;
//outFile.open("StudentGrades.txt");
if (outFile.is_open())
{
cout << "inside if/else outFile" << endl;
//outFile << "File successfully open";
outFile << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
}
else
{
cout << "Error opening file";
}
outFile.close();
/*cout << "Enter 0 for no more students. Enter 1 for more students." << endl;
cin >> choice;
if (choice == 1)
continue;
if (choice == 0)
{
outFile.close();
break;
}*/
}
ifstream inFile;
inFile.open("StudentGrades.txt");
int sTotal;
int total[numStud];
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
total = (quiz1 + quiz2 + quiz3 + quiz4);
sTotal = total[numStud];
double avg = total / 4;
}
system("pause");
return 0;
}
int total[numStud]; is a variable length array and is not standard in C++. If you need an array and you don't know what the size will be then you should use a std::vector. A vector can be used almost exactly as an array can. For example you could would become:
int total;
std::vector<int> studentTotal;
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
studentTotal.push_back(quiz1 + quiz2 + quiz3 + quiz4); // insert into the vector at the end
total += studentTotal.back(); // get last inserted element
}