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

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'))

Related

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

I am getting errors in my C++ program

I am current creating a weather application that is giving me an error. It said there is something wrong with != but I am not sure what is wrong so can anyone help. It is giving me the error operand types are incompatible ("std::string *" and "const char *")(there is 4) and '!=': no conversion from 'const char *' to 'std::string *'
Thank you
C++ code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void moveTemperaturesToRight(double temperatures[], double windSpeed[], string windDirection[])
{
for (int i = 3; i > 0; i--)
{
temperatures[i] = temperatures[i - 1];
windSpeed[i] = windSpeed[i - 1];
windDirection[i] = windDirection[i - 1];
}
}
int main()
{
string name;
int choice;
int numOfReadings = 0;
double temperatures[4], windSpeeds[4];
string windDirections[4];
bool initialized = false;
string str;
//Have the user provide a name for the weather station upon entry.
cout << "Enter the name of weather station: ";
getline(cin, name);
//Control loop to perform various actions.
while (true)
{
cout << "1. Input a complete weather reading." << endl;
cout << "2. Print the current weather." << endl;
cout << "3. Print the weather history (from most recent to oldest)." << endl;
cout << "4. Exit the program." << endl;
cout << "Enter your choice: ";
cin >> str;
if (str.length() != 1 || str < "1" || str > "4")
choice = 0;
else
choice = atoi(str.c_str());
//Switch based on choice.
switch (choice)
{
case 1: moveTemperaturesToRight(temperatures, windSpeeds, windDirections);
do {
cout << "Enter the temperature (a value >=0):";
cin >> temperatures[0];
} while (temperatures < 0);
//get correct wind speed
do
{
cout << "Enter the wind speed (a value >=0):";
cin >> windSpeeds[0];
} while (windSpeeds < 0);
//get correct wind direction
do
{
cout << "Enter the wind direction (North,South,East or West):";
cin >> windDirections[0];
} while (windDirections != "North" && windDirections != "South" && windDirections != "East" && windDirections != "West");
initialized = true;
if(initialized)
numOfReadings++;
if (numOfReadings > 4)
numOfReadings = 4;
break;
case 3: //Print the current weather, if valid weather is entered.
for (int i = 0; i < numOfReadings; i++)
{
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[i] << endl;
cout << "Wind speed: " << windSpeeds[i] << endl;
cout << "Wind direction: " << windDirections[i] << endl << endl;
}
if (numOfReadings == 0)
cout << "Please enter the details before asking to print." << endl;
break;
case 2: if (numOfReadings == 0)
{
cout << "Please enter the details before asking to print." << endl;
break;
}
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[0] << endl;
cout << "Wind speed: " << windSpeeds[0] << endl;
cout << "Wind direction: " << windDirections[0] << endl << endl;
break;
case 4: return 0; //Stops execution.
default: cout << "Invalid choice. Please follow the menu." << endl;
}
}
}
You need to compare an element of windDirections with the literal.
Did you mean windDirections[0] != "North" &c.?
Currently you're attempting to compare an array of std::strings, and so the compiler issues a diagnostic. It does its best in decaying the array to a pointer to std::string (hence the specific error), but then gives up.

C++ cant exit while loop

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.

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 != ' ')

C++ Address Book Array and Textfile

Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}