How to immediately stop/end the program? - c++

The user is asked if s/he wants to return to main menu, if the user inputs n/N it only proceeds to the next solution when it should immediately end the program. Shown below is the code I used for the program. Please help me to make solution on how to end the program immediately when No is chosen as his/her choice. Thank you so much!
void number()
int b=0;
int groupChoice=0;
float ave[groupChoice];
int trials[groupChoice];
float result,sumRes,dAve;
int sumTry=0;
char choice;
cout << "\nNUMBER OF TRIALS" << endl;
cout << "\nHow many groups? ";
cin >> groupChoice;
for (int j=0;j<groupChoice;j++)
{
cout << "Average distance for group " << j+1 << ": ";
cin >> ave[j];
cout << "No. of trials for group " << j+1 << ": ";
cin >> trials[j];
}
cout << "\nGroups\t\tAve. Distance(x)\tNo. of trials(w)\tx(w)" << endl;
for (int i=0;i<groupChoice;i++)
{
result=ave[i]*trials[i];
cout << "Group " << i + 1 << "\t\t" << ave[i] << "\t\t\t" << trials[i] << "\t\t\t" << result << endl;
sumTry=sumTry+trials[i];
sumRes+=result;
}
cout << "\t\t\t\t\tSum = " << sumTry << "\t\tSum = " << sumRes << endl;
dAve = sumRes / sumTry;
cout << "Distance Average is " << dAve << endl << endl;
b=0;
while(b==0)
{
cout << "Would you like to return to main menu? [Y or N]: ";
cin >> choice;
if (choice=='Y'||choice=='y')
{
b++;
system("cls");
a=0;
main();
}
else if (choice=='N'||choice=='n')
{
b++;
break;
}
}

You can terminate your program with
void std::exit( int exit_code );
eg
std::exit(EXIT_SUCCESS);
https://en.cppreference.com/w/cpp/utility/program/exit

There are two options
use
std::exit(<exit_code>); or
std::_Exit(<exit_code>);
more info:
https://en.cppreference.com/w/c/program/_Exit

Related

How to store multiple string inputs and displaying it after

I'm just starting in studying C++, and I am doing a simple challenge which is GWA Calculator, but I am having a problem finding out how to store the multiple strings input (which is the Subjects/Course) and displaying it after together with the Units and Grades. I am really sorry, but I tried finding out how and I couldn't find an answer. Hope you can help me out.
#include <stdlib.h>
using namespace std;
void calculateGWA();
int main()
{
system("cls");
int input;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
cout << "\t\t| GWA Calculator |" << endl;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
cout << "\t\t| MENU:\t\t\t\t\t\t\t " << "|" << endl;
cout << "\t\t| 1. Calculate GWA (General Weighted Average)\t\t " << "|" << endl;
cout << "\t\t| 2. Calculate CGWA (Cummulative Weighted Average) " << "|" << endl;
cout << "\t\t| 4. Exit Application\t\t\t\t\t " << "|" << endl;
cout << "\t\t| |" << endl;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
sub:
cout << "\t\tEnter your choice: ";
cin >> input;
switch(input)
{
case 1:
calculateGWA();
break;
case 2:
//calculateCGPA();
break;
case 3:
main();
break;
case 4:
exit(EXIT_SUCCESS);
break;
default:
cout << "You have entered wrong input.Try again!\n" << endl;
goto sub;
break;
}
}
void calculateGWA()
{
int q;
system("cls");
cout << "-------------- GWA Calculator -----------------"<<endl;
cout << " How many course(s)?: ";
cin >> q;
char c_name[50];
float unit [q];
float grade [q];
cout << endl;
for(int i = 0; i < q; i++)
{
cout << "Enter the Course Name " << i+1 << ": ";
cin >> c_name;
cout << "Enter the Unit " << c_name << ": ";
cin >> unit[i];
cout << "Enter the Grade " << c_name << ": ";
cin >> grade[i];
cout << "-----------------------------------\n\n" << endl;
}
float sum = 0;
float tot;
for(int j = 0; j < q; j++)
{
tot = unit[j] * grade[j];
sum = sum + tot;
}
float totCr = 0;
for(int k = 0; k < q; k++)
{
totCr = totCr + unit[k];
}
system("cls");
// PRINTS OUT THE COURSES - UNITS - GRADES AND GWA //
cout << "\t\t =============================================================== " << endl;
cout << "\t\t| COURSE | UNIT | GRADE |" << endl;
cout << "\t\t =============================================================== " << endl;
cout << "Total Points: " << sum << " \n Total Credits: " << totCr << " \nTotal GPA: " << sum/totCr << " ." << endl;
cout << c_name << "\n" << endl;
cout << "===================================" << endl;
sub:
int inmenu;
cout << "\n\n\n1. Calculate Again" << endl;
cout << "2. Go Back to Main Menu" << endl;
cout << "3. Exit This App \n\n" << endl;
cout << "Your Input: " << endl;
cin >> inmenu;
switch(inmenu)
{
case 1:
calculateGPA();
break;
case 2:
main();
break;
case 3:
exit(EXIT_SUCCESS);
default:
cout << "\n\nYou have Entered Wrong Input!Please Choose Again!" << endl;
goto sub;
}
}

Why the output is not correct and compelete when using pointers in array of structures?

I have written this code using array of structures in C++ and the output was correct, but when I included the pointers, the output is not correct and missing a lot of, what is the reason of this?
This is the code using pointers:
#include <iostream>
using namespace std;
struct Course {
string CourseCode;
string CourseName;
string LecturerName;
};
struct Student {
string StudentID;
string StudentName;
string Nickname;
Course info;
};
void menu(void) {
cout << "=================================" << endl;
cout << " MENU " << endl;
cout << "=================================" << endl;
cout << " 1- Add new students" << endl;
cout << " 2- Display student list" << endl;
cout << " 3- Add new course" << endl;
cout << " 4- Display Course Offered" << endl;
cout << " 5- Exit Program" << endl;
cout << "=================================" << endl << endl;
}
int main()
{
Student *ptr[2] ;
Student details[2];
ptr[2] = &details[2];
int m, option, courNo;
menu();
cout << "Choose an option from the menu: ";
cin >> option;
while (option != 5)
{
if (option == 1) {
// cout << "\nHow many students do you want to enter? ";
// cin >> stuNo;
for (m = 0; m < 2; m++) {
cout << "\nEnter student " << m + 1 << " details: " << endl;
cout << "ID: ";
cin >> ptr[m]->StudentID;
cout << "Name: ";
cin >> ptr[m]->StudentName;
cout << "Nickname: ";
cin >> ptr[m]->Nickname;
}
}
else if (option == 2) {
cout << "\nThe students details you entered are:" << endl;
for (m = 0; m < 2; m++) {
cout << "\nStudent " << m + 1 << ": " << endl;
cout << "ID: " << ptr[m]->StudentID << endl;
cout << "Name: " << ptr[m]->StudentName << endl;
cout << "Nickname: " << ptr[m]->Nickname << endl;
}
}
else if (option == 3) {
cout << "\nHow many courses do you want to enter? ";
cin >> courNo;
for (m = 0; m < courNo; m++) {
cout << "\nEnter course " << m + 1 << " details: " << endl;
cout << "Course Code: ";
cin >> ptr[m]->info.CourseCode;
cout << "Course Name: ";
cin >> ptr[m]->info.CourseName;
cout << "Lecturer Name: ";
cin >> ptr[m]->info.LecturerName;
}
}
else if (option == 4) {
cout << "\nThe courses details you entered are:" << endl;
for (m = 0; m < 2; m++) {
cout << "\nCourse " << m + 1 << ": " << endl;
cout << "Course Code: " << ptr[m]->info.CourseCode << endl;
cout << "Course Name: " << ptr[m]->info.CourseName << endl;
cout << "Lecturer Name: " << ptr[m]->info.LecturerName << endl;
}
}
else
cout << "Invalid number! Please re-enter a choice from the menu." << endl;
cout << "=====================================================" << endl;
cout << "\nChoose an option from the menu: ";
cin >> option;
}
if (option == 5)
cout << "End of program!" << endl;
}
This is the output of the program, after I enter the code it was terminated:
=================================
MENU
=================================
1- Add new students
2- Display student list
3- Add new course
4- Display Course Offered
5- Exit Program
=================================
Choose an option from the menu: 3
How many courses do you want to enter? 2
Enter course 1 details:
Course Code: 123
This is the output without using pointers, it was like this which is the output that I'm looking for:
=================================
MENU
=================================
1- Add new students
2- Display student list
3- Add new course
4- Display Course Offered
5- Exit Program
=================================
Choose an option from the menu: 3
How many courses do you want to enter? 2
Enter course 1 details:
Course Code: 0000
Course Name: course1
Lecturer Name: lecturer1
Enter course 2 details:
Course Code: 1111
Course Name: course2
Lecturer Name: lecturer2
=====================================================
Choose an option from the menu: 5
End of program!

C++ Program need help to debug

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...

C++ contact card, re-running program trouble

For my assignment, I have to make a customer card with some info required. I am able to run the program just fine, but when I re-run it with the "Do you wish to run again? (Y/N)", the first 2 questions appear on the same line and it messes up the program. Could anyone help me fix this issue?
#include <iostream>
#include <cstdlib>
#include <iomanip>
int main()
{
char answer;
system("CLS");
cout << "*********************************************" << endl;
cout << "*********************************************" << endl;
cout << "*** W E L C O M E ! ***" << endl;
cout << "*** In this program you will be creating ***" << endl;
cout << "*** a Customer Contact card! ***" << endl;
cout << "*********************************************" << endl;
cout << "*********************************************" << endl;
system("pause");
do
{
string name;
string city;
string address;
string state;
string phone_number;
string zip;
system("CLS");
cout << endl;
cout << "Enter the name of your contact : ";
getline(cin,name);
cout << "Enter your contact's phone number : ";
getline(cin,phone_number);
cout << "Enter your contact's address : ";
getline(cin,address);
cout << "Enter the city your contact lives in : ";
getline(cin,city);
cout << "Enter the state your contact lives in (Enter the abbreviation) : ";
getline(cin,state);
cout << "Enter your contact's zip code : ";
cin >> zip;
system("pause");
system("CLS");
cout << "*********************************************" << endl;
cout << "*** ***" << endl;
cout << "*********************************************" << endl;
cout << "*** " << name << setw(41- name.length()) << "***" << endl;
cout << "*** " << address << setw(41- address.length()) << "***" << endl;
cout << "*** " << city << " " << state << " , " << zip << setw(30- city.length()) << "***" << endl;
cout << "*** " << state << setw(41- state.length()) << "***" << endl;
cout << "*** ";
cout<<"(";
for(int i = 0; i < 3; i++) {
cout << phone_number[i];
}
cout << ")";
for(int i = 3; i < 6; i++) {
cout << phone_number[i];
}
cout << "-";
for(int i = 6; i < 10; i++) {
cout << phone_number[i];
}
cout << setw(38- phone_number.length()) << "***" << endl;
cout << "*** " << zip << setw(41- zip.length()) << "***" << endl;
cout << "*********************************************" << endl;
cout << "*********************************************" << endl;
cout << endl;
cout << "Do you want to create another contact card? (Y/N)" << endl;
cin >> answer;
}
while (answer == 'Y' || answer == 'y');
return 0;
}
You are mixing cin >> and getline(cin,. So the newline was still stuck in cin by the time you wanted to read the first question's answer on the second run.
Stick to one or the other and this confusing behavior shouldn't present itself.
As mentioned in this answer: you could also add the following after cin >> answer to clear cin up to and including the newline:
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

Why won't my code switch player names correctly after 3 rounds of play?

So in my class I had to make a Numberwang simulation game. Everything works fine except for the fact that after 2 rounds the names don't correlate correctly. It supposed to say "Round 3, Player1 to play first." which it does however player2 comes up as the one to play first.
# include <iostream>
# include <ctime>
# include <cstdlib>
using namespace std;
bool numberwang(int n)
{
if(n < 100 ){
return 1;
} else {
return 0;
}
}
int main()
{
string Firstplayer, Otherplayer;
int rounds;
int counter = 1;
int number;
int win = 18;
int lose= 1;
cout << "Hello, and welcome to Numberwang, the maths quiz that simply everyone is talking about!" << endl;
cout << "What is player 1's name? ";
cin >> Firstplayer;
cout << "What is player 2's name? ";
cin >> Otherplayer;
cout << "How many rounds? ";
cin >> rounds;
cout << "Well, if you're ready, lets play Numberwang!" << endl;
while(counter <= rounds){
cout << "Round " << counter << ", " << Firstplayer << " to play first." << endl;
while(true){
cout << Firstplayer << ": ";
cin >> number;
if(numberwang(number)){
counter++;
if(counter > rounds){
cout << "That's Numberwang!" << endl;
cout << "Final scores: " << Firstplayer << " pulls ahead with " << win << ", and " << Otherplayer << " finishes with " << lose << endl;
break;
}
cout << "That's Numberwang!" << endl;
swap(Firstplayer, Otherplayer);
cout << "Round " << counter << ", " << Firstplayer << " to play first." << endl;
}
cout << Otherplayer << ": ";
cin >> number;
if(numberwang(number)){
counter++;
if(counter > rounds){
cout << "That's Numberwang!" << endl;
cout << "Final scores: " << Firstplayer << " pulls ahead with " << win << ", and " << Otherplayer << " finishes with " << lose << endl;
break;
}
cout << "That's Numberwang!" << endl;
swap(Firstplayer, Otherplayer);
cout << "Round " << counter << ", " << Firstplayer << " to play first." << endl;
}
}
}
return 0;
}
After your if-statement (line 61) you say 'Firstplayer' and then you output the 'Otherplayer'. The names do not match.
Blockquote
cout << "Round " << counter << ", " << Firstplayer << " to play first." << endl;
}
cout << Otherplayer << ": ";
cin >> number;