C++ cant exit while loop - c++

So for my program of manipulating a vector, a choice is presented at the end of each switch case: If the letter 'q' is entered, the program is supposed to exit the while loop and end the program, but when I enter the letter 'q', the program crashes instead of exiting properly. Why is this happening? Is it an infinite loop?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int rnum;
int jnum;
int i;
int lim = 5;
char choice='b';
vector<int> jersey(lim);
vector<int> rating(lim);
cout << "MENU" << endl;
cout << "a - Add player" << endl;
cout << "d - Remove player" << endl;
cout << "u - Update player rating" << endl;
cout << "r - Output players above a rating" << endl;
cout << "o - Output roster" << endl;
cout << "q - Quit" << endl;
cout << "" << endl;
cout << "Choose an option:" << endl;
cin >> choice;
while(choice != 'q') {
switch(choice) {
case 'a' :
// addplayer
for(int i = 0; i<=lim-1; i++)
{
cout << "Enter a new player's jersey number:" << endl;
cin >> jersey.at(i);
cout <<"Enter the player's rating:" << endl;
cin >> rating.at(i);
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
case 'u' :
// updat rating
cout << "Enter a jersey number:" << endl;
cin >> jnum;
for( int i = 0; i <= lim-1; i++ )
{
if( jersey.at(i) == jnum )
{
cout << "Enter a new rating for player:" <<endl;
cin >> rnum;
rating.at(i) = rnum;
break;
}
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
case 'o':
cout << "ROSTER" << endl;
for(int i = 0; i<lim; i++)
{
cout << "Player "<<i+1 <<" -- Jersey number:" << " " <<jersey.at(i) << ", " << "Rating: " << rating.at(i) << endl;
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
case 'd':
cout << "Enter a jersey number:" << endl;
cin >> jnum;
for( std::vector<int>::iterator spot = jersey.begin(); spot != jersey.end(); ++spot )
{
if( *spot == jnum )
{
jersey.erase( spot );
rating.erase( spot );
lim = jersey.size();
}
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
case 'r':
cout << "Enter a rating:" << endl;
cin >> rnum;
for( int i = 0; i <= lim-1; i++ )
{
if( rating.at(i) >= rnum )
{
cout << "Player "<<i+1 <<" -- Jersey number:" << " " <<jersey.at(i) << ", " << "Rating: " << rating.at(i) << endl;
}
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
default:
cout << "Choose an option:" << endl;
cin >> choice;
break;
}
}
return 0;
}

Your case 'd' looks incorrect. You can't use spot to erase an element from rating since spot only iterates over jersey's elements. To fix this, and potentially solve your crash or infinite loop issue, you can replace the following code:
if( *spot == jnum )
{
jersey.erase( spot );
rating.erase( spot );
lim = jersey.size();
}
With:
if( *spot == jnum )
{
jersey.erase( spot );
rating.erase( rating.begin() + (spot - jersey.begin()) );
lim = jersey.size();
}
Here, spot - jersey.begin() will give you the index of the jersey you just found, adding that to rating.begin() will therefore give you the corresponding rating and allow you to properly erase it from the rating vector.
In addition, since your code allows duplicate jersey numbers, deleting a duplicate won't always delete all instances of the number. If you want to fix this, you can add spot--; after lim = jersey.size(); to ensure you don't skip over duplicate elements.

Related

Keep receiving this error main.cpp:9:91: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘const std::vector’

Sorry in advance if this is lengthy. the problem is within line 9. (where the 2nd cout is.) apparently, but i'm new to this so I can't identify exactly what the issue is.
#include <iostream>
#include <vector>
using namespace std;
void outputRoster(const vector<int> &jersey, const vector<int> &ratings) {
cout << "ROSTER" << endl;
for (int i =1; i < jersey.size(); ++i) {
cout << "Player " << i << " -- Jersey number: " << jersey.at(i-1) << ", Rating: " << ratings << endl;
}
cout << endl;
}
void addPlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter another player's jersey number: ";
cin >> num;
jersey.push_back(num);
cout << "Enter another player's ratings: ";
cin >> num;
cout << endl;
ratings.push_back(num);
}
void removePlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter a jersey number: ";
cin >> num;
cout << endl;
for (int i = 0; i < jersey.size(); ++i){
if (jersey.at(i)==num){
jersey.erase(jersey.begin()+i);
ratings.erase(ratings.begin()+i);
break;
}
}
}
void updatePlayerRating(const vector<int> &jersey, vector<int> &ratings){
int num;
cout << "Enter a jersey number: " << endl;
cin >> num;
for (int i = 0; i < jersey.size(); ++i){
if(jersey.at(i) == num){
cout << "Enter a new rating for player: ";
cin >> num;
cout << endl;
ratings.at(i) = num;
}
}
}
void outputPlayersAboveRating(const vector<int> &jersey, const vector<int> &ratings) {
int num;
cout << "Enter a rating: ";
cin >> num;
cout << endl;
cout << "ABOVE " << num << endl;
for (int i = 0; i < ratings.size(); ++i){
if (ratings.at(i) > num) {
cout << "Player " << i+1 << " -- Jersey number: " << jersey.at(i) << ", Rating: " << ratings.at(i);
}
}
cout << endl;
}
int main() {
vector<int> jersey;
vector<int> ratings;
for (int i = 0; i < 5; ++i) {
int num;
cout << "Enter player " << i+1 << "'s jersey number:";
cin >> num;
jersey.push_back(num);
cout << "Enter player " << i+1 << "'s ratings:";
cin >> num;
ratings.push_back(num);
cout << endl;
cout << endl;
}
outputRoster(jersey, ratings);
char inp;
while(true) {
cout << "MENU" << endl;
cout << "a - Add player" << endl;
cout << "d - Remove player" << endl;
cout << "u - Update player rating" << endl;
cout << "r - Output players above a rating" << endl;
cout << "o - Output roster" << endl;
cout << "q - Quit" << endl;
cout << "Choose an option: ";
cin >> inp;
cout << endl;
if (inp == 'a') {
addPlayer(jersey, ratings);
}
else if (inp == 'd') {
removePlayer(jersey, ratings);
}
else if (inp == 'u') {
updatePlayerRating(jersey, ratings);
}
else if (inp == 'r') {
outputPlayersAboveRating(jersey, ratings);
}
else if (inp == 'o') {
outputRoster(jersey, ratings);
}
else if (inp == 'q') {
return 0;
}
}
return 0;
}
Any and all help is appreciated also if possible, could you explain how to avoid an error like this in the future.
Thanks in advance.
You cannot print ratings directly in
cout ... << ratings ... because std::vector doesn't have an operator overload for printing. Rather, you have to print out an element inside that vector, so change it to cout ... << ratings[i] ..., which I'm assuming is your desired effect.
This is exactly what the compiler error is telling you. std::vector doesn't have an overload (no operator<< match).

How I can use CASE in a different way? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Hello I am trying to build a project but the case '2' is not working.
struct student
{
string fname;//for student first name
string lname;//for student last name
string id;//for Registration No number
string course;//for class info
}studentData;//Variable of student type
struct teacher
{
string fname;//first name of teacher
string lname;//last name of teacher
string id;//Bool Group
string course;//Number of serves in School
}teach;//Variable of teacher type
int main()
{
int i = 0, j;//for processing usage
char choice;//for getting choice
string find;//for sorting
string srch;
while (1)//outer loop
{
system("cls");//Clear screen
//Level 1-Display process
cout << "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\";
cout << "\n\n\t\t\tSCHOOL MANAGEMENT PROGRAM\n\n";
cout << "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\";
cout << "\n\n\t\t\tMAIN SCREEN\n\n";
cout << "Enter your choice: " << endl;
cout << "1.Students information" << endl;
cout << "2.Teacher information" << endl;
cout << "3. Course information " << endl;
cout << "4. Display Strudent information " << endl;
cout << "5. Display Teacher Information " << endl;
cout << "6. Display Course Information n" << endl;
cout << "7.Exit program" << endl;
cin >> choice;
system("cls");//Clear screen
switch (choice)//First switch
{
case '1': //Student
{
{ ofstream f1("student.txt", ios::app);
for (i = 0; choice != 'n'; i++)
{
if ((choice == 'y') || (choice == 'Y') || (choice == '1'))
{
cout << "Enter First name: ";
cin >> studentData.fname;
cout << "Enter Last name: ";
cin >> studentData.lname;
cout << "Enter Registration number: ";
cin >> studentData.id;
cout << "Enter class: ";
cin >> studentData.course;
f1 << studentData.fname << endl << studentData.lname << endl << studentData.id << endl << studentData.course << endl;
cout << "Do you want to enter data: ";
cout << "Press Y for Continue and N to Finish: ";
cin >> choice;
}
}
f1.close();
}
continue;//control back to inner loop -1
continue;//Control pass to 1st loop
}
case '2'://Teachers biodata
{
{ ofstream t1("teacher.txt", ios::app);
for (i = 0; choice != 'n'; i++)
{
if ((choice == 'y') || (choice == 'Y') || (choice == '1'))
{
cout << "Enter First name: ";
cin >> teach.fname;
cout << "Enter Last name: ";
cin >> teach.lname;
cout << "Enter Registration number: ";
cin >> teach.id;
cout << "Enter class: ";
cin >> teach.course;
t1 << teach.fname << endl << teach.lname << endl << teach.id << endl << teach.course << endl;
cout << "Do you want to enter data: ";
cout << "Press Y for Continue and N to Finish: ";
cin >> choice;
}
}
t1.close();
continue;//control back to inner loop -1
}
continue;//Control pass to 1st loop
}
case '3':
{
{ ifstream f2("student.txt");
cout << "Enter First name to be displayed: ";
cin >> find;
cout << endl;
int notFound = 0;
for (j = 0; (j < i) || (!f2.eof()); j++)
{
getline(f2, studentData.fname);
if (studentData.fname == find)
{
notFound = 1;
cout << "First Name: " << studentData.fname << endl;
cout << "Last Name: " << studentData.lname << endl;
getline(f2, studentData.id);
cout << "Registration No number: " << studentData.id << endl;
getline(f2, studentData.course);
cout << "Class: " << studentData.course << endl << endl;
}
}
if (notFound == 0) {
cout << "No Record Found" << endl;
}
f2.close();
cout << "Press any key two times to proceed";
_getch();//To hold data on screen
_getch();//To hold data on screen
}
continue;//control back to inner loop -1
}
case '4':
{
{ ifstream t2("teacher.txt");
cout << "Enter First name to be displayed: ";
cin >> find;
cout << endl;
int notFound = 0;
for (j = 0; (j < i) || (!t2.eof()); j++)
{
getline(t2, studentData.fname);
if (studentData.fname == find)
{
notFound = 1;
cout << "First Name: " << studentData.fname << endl;
cout << "Last Name: " << studentData.lname << endl;
getline(t2, teach.id);
cout << "Registration No number: " << studentData.id << endl;
getline(t2, teach.course);
cout << "Class: " << studentData.course << endl << endl;
}
}
if (notFound == 0) {
cout << "No Record Found" << endl;
}
t2.close();
cout << "Press any key two times to proceed";
_getch();//To hold data on screen
_getch();//To hold data on screen
}
continue;//control back to inner loop -1
}
case '5':
{}
case '6':
{}
case '7':
{
break;//outer case 3
}//outer case 3
break;//outer loop
}
}
}
inside your switch statement, inside the case where you are checking if "choice" is '2 (case '2'://Teachers biodata), you have yet another if statement which checks if "choice" is '1', but at that point "choice" will be '2'.
if ((choice == 'y') || (choice == 'Y') || (choice == '1'))
becomes
if ((choice == 'y') || (choice == 'Y') || (choice == '2'))

different option throw an unexpected error

when I'm executing this program, it works fine just for one option, but if I try to choose an other option when executing, it will throw an error in this line:
cout << "The available quantity is: " << *(it->second.find(disp)) << endl;
here's my program:
void avail_art(void)
{
char c,con;
int quantity,disp=MAX;
bool b = true;
map<string, unordered_set<int>>m{
{"Mouse",{120,disp}},
{"Keyboard",{75,disp}},
{"Monitor",{750,disp}},
{"GPU",{1200,disp}},
{"CPU",{1000,disp}}
};
auto it = m.find("CPU");
cout << "M - for mouse." << endl;
cout << "K - for keyboard." << endl;
cout << "R - for monitor." << endl;
cout << "G - for GPU." << endl;
cout << "C - for CPU." << endl;
cout << "Q - for quit." << endl;
cout << "======================" << endl;
while (b)
{
cout << "Enter your choice: ";
cin >> c;
switch (c)
{
case 'M':
it = m.find("Mouse");
cout << "You've choosen the Mouse!" << endl;
cout << "The available quantity is: " << *(it->second.find(disp)) << endl;
l:
cout << "Enter the quantity: ";
cin >> quantity;
if (quantity > * (it->second.find(disp)))
{
cout << "Out of Stock! the Stock has only :" << *(it->second.find(disp)) <<" Piece."<< endl;
goto l;
}
cout << "Confirm? y/n: ";
cin >> con;
if (con == 'y')
{
auto its=it->second.find(disp);
it->second.insert(disp=(*its - quantity));
it->second.erase(its);
}
break;
case 'K':
it = m.find("Keyboard");
cout << "You've choosen the Keyboard!" << endl;
cout << "The available quantity is: " << *(it->second.find(disp)) << endl;
cout << "Enter the quantity: ";
cin >> quantity;
cout << "Confirm? y/n :";
cin >> con;
if (con == 'y')
{
auto its = it->second.find(disp);
it->second.insert(disp = (*its - quantity));
it->second.erase(its);
}
break;
}
}
}
can someone help me please

Sporadic infinite loop during do-while c++

Sometimes when I run the program, it runs perfectly fine. Sometimes I get an infinite loop that just keeps displaying my first choice menu. I tried searching for the error and I couldn't figure it out. I thought there was an error in my input statement when I got the menuChoice, but I was unable to troubleshoot it out. Should I be checking the value of menuChoice more often? To better specify, I am referring to the second do-while loop, the one that reprints the menu choices after each iteration.
main.cpp
#include <vector>
#include <fstream>
#include <iostream>
#include "course.hpp"
using namespace std;
int main() {
int menuChoice, searchMenuChoice;
string fileName;
string line;
ifstream inStream;
string searchName;
string searchPrefix;
int searchNum;
vector<Course> courseList;
vector<int> enrolledClasses;
do{
cout << "Please enter the file that contains othe course data: ";
cin >> fileName;
inStream.open(fileName);
}while (!inStream.is_open());
cout << endl;
while (getline(inStream, line)){
courseList.push_back(Course(line));
}
cout << "Welcome to Banner NE, short for Never Existed!" << endl;
do {
cout << "\n"<< "---------------------------------------------" << endl;
cout << "1 - List all available classes" << endl;
cout << "2 - Search for a course" << endl;
cout << "3 - View your current enrolled courses" << endl;
cout << "4 - Enroll in course" << endl;
cout << "5 - Exit" << endl;
cout << "Make your selection here: ";
cin >> menuChoice;
cout << endl;
if (menuChoice == 5){
cout << "Thank you for using Banner NE and have a nice day!" << endl;
return 0;
}
if (menuChoice == 2) {
cout << endl;
cout << "Would you like to search by" << endl;
cout << "1 - Course number" << endl;
cout << "2 - Available seats remaining" << endl;
cout << "3 - Instructor name" << endl;
cout << "4 - Course prefix" << endl;
cout << "Make your selection: ";
cin >> searchMenuChoice;
if (searchMenuChoice == 2) {
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).getSeatsRemaining() > 0)
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 1) {
cout << "Please enter the course number: ";
cin >> searchNum;
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).MatchesCourseNumberSearch(searchNum))
courseList.at(i).printCourse();
break;
}
}
if (searchMenuChoice == 3) {
cout << "Please enter the name of the instructor: ";
cin >> searchName;
for (int i = 0; i < courseList.size(); i++) {
if (courseList.at(i).MatchesInstructorSearch(searchName))
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 4){
cout << "Please enter the prefix you would like to search for: ";
cin >> searchPrefix;
for (int x = 0; x < courseList.size(); x++)
if (courseList.at(x).MatchesPrefix(searchPrefix))
courseList.at(x).printCourse();
}
}
if (menuChoice == 1) {
for (int x = 0; x < courseList.size(); x++){
cout << "ID: " << x << "\t";
courseList.at(x).printCourse();
cout << endl;
}
}
if (menuChoice == 4) {
int classEnrollment;
cout << "Please enter the ID number of the class you would like to enroll: ";
cin >> classEnrollment;
if (courseList.at(classEnrollment).Enroll()){
enrolledClasses.push_back(classEnrollment);
cout << "You have enrolled in ID " << classEnrollment << endl;
}
else
cout << "There was not enough space, sorry." << endl;
}
if (menuChoice == 3){
for (int i = 0; i < enrolledClasses.size(); i++){
courseList.at(enrolledClasses.at(i)).printCourse();
cout << endl;
}
if (enrolledClasses.size() == 0 )
cout << "You are not currently enrolled in any classes." << endl;
}
} while (menuChoice != 5);
return 0;
}

C++ my program reads backspace as a character

I am working with a c++ program, but I am stuck with annoying bug. The bug is that when i type the password, it counts backspace as a character so can I fix it? Here is the code.
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
string password, username, lon, nu, np;
char c;
int StarNum = 0, humanproof;
cout << "Do you wanna create a user or login?";
cout << "\nLogin" << endl;
cout << "New" << endl;
cin >> lon;
if(lon=="login"){
goto login;
}
if(lon=="new"){
goto newa;
}
login:
cout << "Username: ";
cin >> username;
lol:
cout << "Password: ";
while (c != 13)
{
c = (char)getch();
if(c == 13) break;
StarNum++;
password += c;
cout << "*";
if (c == 127 || c == 8){
//go here to fix the problem
}
password = "";
goto lol;
}
}
if(username == "user" && password == "pass" || username == nu && password == np){
cout << "\nYou are logged in.";
goto options;
} else {
cout << "\nusername or password is wrong" << endl;
return 0;
}
return 0;
newa:
cout << "Username:";
cin >> nu;
cout << "password:";
cin >> np;
cout << "Type the number fourhoundred and twentie three too proof you are a human: ";
cin >> humanproof;
if(humanproof == 423){
cout << "The username is " << nu << endl;
for(int no = 0; no <= 100; no++){
cout << endl;
}
goto login;
return 0;
}
if(humanproof!=423){
cout << "wrong answer!";
return 0;
}
options:
int op;
cout << "\nwhat do you want to do?" << endl;
cout << "1. Calculator" << endl;
cout << "2. About"<< endl;
cout << "3. Just for fun" << endl;
cout << "4. Exit" << endl;
cin >> op;
if(op==1){
goto calculator;
}
if(op==2){
goto info;
}
if(op==3){
goto fun;
}
if(op==4){
return 0;
}
else{
cout << "you entered a invalid number. " << endl;
return 0;
}
calculator:
double n1, n2, sum;
int opa;
cout << "Choose a operation" << endl;
cout << "1. Addition/+" << endl;
cout << "2. Subscraction/-" << endl;
cout << "3. Multiplication/x" << endl;
cout << "4. Divsion/ /" << endl;
cin >> opa;
if(opa == 1){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 + n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 2){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 - n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 3){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 * n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 4){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 / n2;
cout << "the sum is " << sum;
return 0;
}
if(opa > 4){
cout << "You entered a invalid number";
goto calculator;
}
info:
cout << "Created by Bergur 2013";
return 0;
fun:
cout << "You want an eyepad(ipad)?";
}
Your code already checks:
while (c != 13)
And prevent newline from being handled, do similar to what you need with the backspace character, whose number is 8
To fix your issue, before:
StarNum++;
Add:
if (c == 8 && StarNum > 0) {
StarNum--;
if (password.size () > 0)
password.resize (password.size () - 1);
continue;
}
Please format your code. Also, try to provide a minimal code which reproduce the problem, not the whole code.
Unrelated to your problem
Try not to use goto.
Do not use ASCII values, but use the char literals instead, i.e. use '\n' instead of 13.
Also, you can simply add an iother condition inside your while:
while (c != '\n' && c != ' ')