Program doesn't execute for loop until the end - c++

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.

Related

Why my array doesn't print different subjects name inputted by a user?

The objective is to take input of subjects and their marks from a user and finally display them as a report card. Everything works as expected except that the compiler prints the name of the last subject entered for each different subject name in the final report.
Here is the C++ code that I tried:
#include <iostream>
using namespace std;
int main() {
string fname, lname;
int subjects;
float totalMarks;
cout << "Enter your first name: ";
cin >> fname;
cout << "Enter your last name: ";
cin >> lname;
cout << "Enter total marks: ";
cin >> totalMarks;
cout << "Marks of how many subjects: ";
cin >> subjects;
float subjectMarks[subjects];
string subjectNames[subjects];
for (int i = 0; i < subjects; i++) {
for (int j = 0; j < subjects; j++) {
cout << "Enter name of subject: ";
cin >> subjectNames[j];
break; // I've used 'break' to exit the inner loop and go to outer loop for
// entering the marks obtained in the subject
};
cout << "Enter marks obtained in the subject: ";
cin >> subjectMarks[i];
};
cout << "Dear, " << fname << " " << lname << "! The subjects and their marks are shown below: \n";
cout << "RESULTS IN SUBJECTS\n\n";
for (int i = 0; i < subjects; i++) {
for (int j = 0; j < subjects; j++) {
cout << subjectNames[j] << "\t\t";
break;
}
cout << subjectMarks[i] << endl;
};
return 0;
}
What I expected?
As you can see in the screenshot, 'Chemistry' is printed twice with different marks. It should have printed first 'Physics' with marks '80' and then 'Chemistry' with marks '70' as inputted by the user. I doubt there is a problem with subjectNames[] array.
But this is what actually happened
enter image description here
I'm stuck on this problem for more than 3 hours. Please help!
The loop for reading and the loop for writing is wrong. You don't need nested loops. Just have one variable when reading and one when writing:
// reading
for (int i = 0; i < subjects; i++) {
std::cout << "Enter name of subject: ";
std::cin >> subjectNames[i];
std::cout << "Enter marks obtained in the subject: ";
std::cin >> subjectMarks[i];
};
// writing
std::cout << "Dear, " << fname << " " << lname
<< "! The subjects and their marks are shown below:\n"
"RESULTS IN SUBJECTS\n\n";
for (int i = 0; i < subjects; i++) {
std::cout << subjectNames[i] << "\t\t"
<< subjectMarks[i] << '\n';
}
Also note that your subjectMarks and subjectNames are Variable Length Arrays (VLAs) and those aren't supported in standard C++. Only some compilers supports them as an extension. I recommend that you use std::vectors instead:
#include <vector>
// ...
std::vector<float> subjectMarks(subjects);
std::vector<std::string> subjectNames(subjects);

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

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:

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.

c++ why is there still input buffer left?

After my first entry, my second entery name field fills up with the input buffer from the previous entry. Why? I am even using the getline but the problem still persists. Please help me with the problem. This is question from Jumping Into C++ book .
#include <iostream>
#include <string>
using namespace std;
struct Person
{
string name;
string address;
long long int PhoneNumber;
};
void displayEntries(Person p[])
{
int enteryNumber;
cout << "Enter the entry number of the person for details(enter 0 to display all entries): ";
cin >> enteryNumber;
if(enteryNumber == 0)
{
for(int i = 0; i < 10; i++)
{
cout << "Entery Number: " << i + 1;
cout << "Name: " << p[i].name << endl;
cout << "Address: " << p[i].address << endl;
cout << "Phone Number: " << p[i].PhoneNumber << endl;
}
}
do
{
cout << "Entery Number: " << enteryNumber;
cout << "Name: " << p[enteryNumber].name << endl;
cout << "Address: " << p[enteryNumber].address << endl;
cout << "Phone Number: " << p[enteryNumber].PhoneNumber << endl;
} while (enteryNumber != 0);
}
int main()
{
Person p[10];
for(int i = 0; i < 10; i++)
{
cout << "Enter the details of the person\n\n";
cout << "Name: ";
getline(cin, p[i].name);
cout << "Address: ";
getline(cin, p[i].address);
cout << "Phone Number: ";
cin >> p[i].PhoneNumber;
cout << endl;
}
displayEntries(p);
return 0;
}
You can see what is happening when you read the reference for getline:
When used immediately after whitespace-delimited input, e.g. after
int n;
std::cin >> n;
getline(cin, n); //if used here
getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
before switching to line-oriented input.
cin >> p[i].PhoneNumber; only gets the number. That leaves the line ending still in the input buffer to be read the next time you try to read a line.

Do-While Loop C++ [duplicate]

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");
}