For loop and Arrays [C++ Simple ATM system] - c++

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:

Related

Program doesn't execute for loop until the end

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.

fix repeating "enter names of teacher" after I finish the input?

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.

How to display user account only using user ID num

Im basically making a database that stores a users account info. (Name, Phone number, ID, etc) I want to be able to display a specific persons info by entering in their ID num.
I have a struct with basic info and an array struct that stores each person and their info. I need to be able to type in a persons ID and have it display their info.
(I am still in first year of CS degree plz be gentle lol)
struct Account{
string name;
string city;
string state;
int ZIP;
int phone;
int IDNUM;
double ACT_BAL;
string LST_PMNT;};
Main fuction
const int SIZE = 20;
Account customers[SIZE];
const int NEW_INFO = 1, CHNG_INFO = 2, DISP = 3, EXIT = 4;
char choice1;
int choice;
int n;
int NEWCUST;
int results;
do
{ // menu display
cout << "Customer Database\n"
<< "----------------------------\n"
<< "1. Enter new account info\n"
<< "2. Change account info\n"
<< "3. Display all account info\n"
<< "4. Exit\n";
cin >> choice;
//respond to user input
switch (choice)
case NEW_INFO:
cout << "Would you like to enter a new cusomter?\n"
<< "(Y/N)";
cin >> choice1;
if (choice1 == 'Y' || choice1 == 'y')
{
cout << "How many new customers?" << endl; //User eneters in new customer info without having to enter in a full array worth of customers.
cin >> NEWCUST;
for (n = 0; n < NEWCUST; n++)
{
cout << "ID Number: ";
cin >> customers[n].IDNUM;
cout << "Enter in a name: ";
cin >> customers[n].name;
cout << "City: ";
cin >> customers[n].city;
cout << "State: ";
cin >> customers[n].state;
cout << "ZIP code: ";
cin >> customers[n].ZIP;
cout << "Phone number: ";
cin >> customers[n].phone;
cout << "Account Balance: ";
cin >> customers[n].ACT_BAL;
cout << "Lasy payment date: ";
cin >> customers[n].LST_PMNT;
}
}
break;
case CHNG_INFO: // Changes info
break; // displays all info (work in progress)
case DISP:
cout << "Enter customers ID number" << endl;
cin >> customers[].IDNUM;
results = linearSearch(customers, SIZE, customers[].IDNUM);
break;
case EXIT:
cout << "Cosing......" << endl; //exits progeam
break;
To get a specific user details, you can do the following:
Declaring num as short int to hold a simple User ID, you can change it. N = 50 as you've provided the constant. Now, unless the loop finds the inputted ID matching with one of the struct's idNum, it'll be executed 50 times (max).
cout << "Input account code: ";
cin >> num;
for (int i = 0; i < N; i++)
{
if (num == acc[i].idNum)
{
cout << "Name: " << acc[i].name << endl
<< "..." << endl;
}
}

Identifier undefined and incompatible declaration

I am new to c++ and my textbook is not very helpful. I have a few errors in my code. Where I am being told the identifier for customerAccount is undefined, and I have an incompatible declaration with my int search before and after my main. I will post some code below as I have been trying to figure this out for a while and I am at a loss.
#include<iostream>
#include<string>
using namespace std;
struct {
string Name;
string Address;
string City_State_Zip;
double phoneNumber;
double actBalance;
string Payment;
};
//This is where the errors start, saying customer account is undefined
void Display(customerAccount ca);
//declaration is incompatible with int search
int Search(customerAccount, string);
int main() {
customerAccount customers[10];
string SName;
int choice, i = 0, size = 0;
do {
cout << "****Menu****" << endl;
cout << "1. Enter Customer Information" << endl;
cout << "2. Change Customer Information" << endl;
cout << "3. Search For Customer" << endl;
cout << "4. Display Customer Data" << endl;
cout << "5. Exit" << endl;
cout << "Please enter a choice 1,2,3,4 or 5";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter customer name: ";
cin >> customers[i].Name;
cout << "Enter customer address: ";
cin >> customers[i].Address;
cout << "Enter city state and zip: ";
cin >> customers[i].City_State_Zip;
cout << "Enter phone number: ";
cin >> customers[i].phoneNumber;
cout << "Enter account balance: ";
cin >> customers[i].actBalance;
if (customers[i].actBalance < 0) {
cout << "Account balance cannot be negative. Please re-enter: "
<< endl;
cin >> customers[i].actBalance;
}
cout << "Enter last payment: ";
cin >> customers[i].Payment;
i++;
break;
case 2: int ele;
cout << "Enter customer information to modify: " << endl;
cout << "Enter customer name: ";
cin >> customers[ele - 1].Name;
cout << "Enter customer address: ";
cin >> customers[ele - 1].Address;
cout << "Enter city state and zip";
cin >> customers[ele - 1].City_State_Zip;
cout << "Enter phone number: ";
cin >> customers[ele - 1].phoneNumber;
cout << "Enter account balance: ";
cin >> customers[ele - 1].actBalance;
if (customers[ele - 1].actBalance < 0) {
cout << "Account balance cannot be negative. Please re-enter: "
<< endl;
cin >> customers[i].actBalance;
}
cout << "Enter date of payment: ";
cin >> customers[ele - 1].Payment;
break;
case 3: cout << "Enter customer name to search: ";
cin >> SName;
for (size = 0; size < i; size++) {
int check;
check = Search (customers[size], SName);
if (check == 1)
Display(customers[size]);
}
break;
case 4:
for (size = 0; size < i; size++)
Display(customers[size]);
break;
case 5: exit(0);
break;
}
} while (choice != 5);
system("pause");
return 0;
}
void Display(customerAccount ca) {
cout << " Customer name:";
cout << ca.Name << endl;
cout << " Address:";
cout << ca.Address << endl;
cout << " city state and zip:";
cout << ca.City_State_Zip << endl;
cout << " Phone number:";
cout << ca.phoneNumber << endl;
cout << " Account balance:";
cout << ca.actBalance << endl;
cout << " Date of payment:";
cout << ca.Payment << endl;
}
//declaration is incompatible with int search
int Search(customerAccount ca, string str) {
if (str.compare(ca.Name) == 0)
return 1;
else
return 0;
}
case 2: int ele;
On this line you have an uninitialized variable which is causing your bug.

How would i reject invalid inputs in my code?

I have no idea how i would reject invalid inputs for the exams and assignments (valid numbers are 0.00 - 100.00). but i also need to give the user one more chance to enter a valid input. so if they put in two invalid inputs in a row for the same variable it tells the user that they need to restart the program and prevent it from running. Im new to programming so im not very good at this.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main ()
{
float exam_1;
float exam_2;
float exam_3;
float assignment_1;
float assignment_2;
float weighted_exam = .1667;
float weighted_assignment = .25;
float min_score = 0.00;
float max_score = 100.00;
string name;
cout << "Please enter student name <First Last>: "; // this will ask for the students first and last name
getline(cin, name);
cout << "\n";
cout << "\t Be sure to include the decimal point for scores.\n";
cout <<"\t !!! All scores should range from 0.00 to 100.00!!! \n";
cout << "\t For example: 80.50 \n";
cout << "\n";
cout << "Please enter your exam 1 score: ";
cin >> exam_1;
cout << "Please enter your exam 2 score: ";
cin >> exam_2;
cout << "Please enter your exam 3 score: ";
cin >> exam_3;
cout << "Please enter your assignment 1 score: ";
cin >> assignment_1;
cout << "Please enter your assignment 2 score: ";
cin >> assignment_2;
cout << endl;
cout << "-" << "OUTPUT" << "-\n";
return 0;
}
You can do like this:
do{
cout <<"\t !!! All scores should range from 0.00 to 100.00!!! \n";
cin >> exam_1;
while(exam_1 < 0.0 || exam_1>100.0);
Repeat this to all inputs
cout << "Please enter your exam 1 score: ";
cin >> exam_1;
cout << "Please enter your exam 2 score: ";
cin >> exam_2;
cout << "Please enter your exam 3 score: ";
cin >> exam_3;
To
auto ReadExamScore = [](auto& ex, char c)
{
cout << "Please enter your exam " << c << " score: ";
for (int i = 0; i < 2; i ++)
{
if (cin >> ex)
{
if (ex>= 0.0 && ex <= 100.00)
return true;
}
cout << "Please enter a valid exam score" << endl;
}
cout << "Press any key to exit..." << endl;
getchar();
exit(0);
};
ReadExamScore(exam_1,'1');
ReadExamScore(exam_2,'2');
ReadExamScore(exam_3,'3');