Switch Statement Goes Straight to Default Regardless of Correct Value - switch-statement

/*
Generate a Sales Report:
(+) 1. Use enum to use salespersons' names as values
2. File format with person's last name
-each salesperson gets seperate file (.dat extension)
3. line in file contains item#, last name, and quantity
-1 file created for each item
4. Invalid salepersons' names generate error message
5. Invalid product number generates error message & written to salespersons' file
-don't compute total 4 item then!!!
Givens
8 products list:
item #7 #$345.00
item #8 #$853.00
item #9 #$471.00
item #10 #$933.00
item #11 #$721.00
item #12 #$663.00
item #13 #$507.00
item #14 #$259.00
*/
#include<iostream>
#include<fstream>
#include<string>
#include<cctype>
using namespace std;
enum Salesperson{ Dixon, Bolly, Ki, Kee, Niles, Hamil, Cams, Tyson };
string repname[]={"Dixon", "Bolly","Ki", "Kee", "Niles","Hamil","Cams","Tyson"};
struct Salespeople
{
string lname;
int itemnum;
int quantity;
float price;
}
;
Salespeople salesrep[8]; //for the 8 salesreps
//Name (string) Verification Functions
string toUpper(string s)
{
for (int i = 0; i < s.size(); i++)
{
s[i] = toupper(s[i]);
}
return s;
}
int placement(string s)
{
int verified = -1;
for ( int i= 0; i < 8; i++)
{
if(s == repname[i])
verified = i;
}
return verified;
}
///////////////////////////////
int main()
{
//File I/O Setup
ofstream inputfile ("salesheet.txt"); //input file will be called salesheet.txt
inputfile <<"Salesperson \t\t"<<"Item # \t\t"<< "Quantity";
inputfile.close();
////////
cout << "\n These Are SalesRep Names";
/*
1. for loop used to loop switch statement
- looped switch statement allows for programmer and user to have more freedom of how
information is inputted/outputted
-for whatever reason wrong information is entered, user/programmer can decide at what point
to start from
-for loop used soley for this utility doesn't allow to start from a special point; for
loops force user through entire loop
-if forced to re-enter information through entire loop, file could be overwritten and/or
contain duplicates
*/
int i;
for( i = 0; i < 8; i++)
{
cout <<"\n\t";
cout << repname[i];
}
int rep;
int go;
for( go = 0; go < 8; go++)
{
string name;
cout << "\n\n Enter SalesRep Name: ";
cin >> name;
//These below functions make use of the enum.
name = toUpper(name);
rep = placement(name);
switch(rep)
{
case Dixon:
cout <<"\n Salesperson Dixon, put in Last Name";
cin >> salesrep[1].lname;
cout << "\n Enter Item#: ";
cin >> salesrep[1].itemnum;
cout <<"Enter Item Quantity";
cin >>salesrep[1].quantity;
inputfile <<"\n"<< salesrep[1].lname <<"\t" << salesrep[1].itemnum <<"\t" <<salesrep[1].quantity;
break;
case Bolly:
cout <<"\n Salesperson Bolly, put in Last Name";
cin >> salesrep[2].lname;
cout << "\n Enter Item#: ";
cin >> salesrep[2].itemnum;
cout <<"\n Enter Item Quantity";
cin >>salesrep[2].quantity;
break;
case Ki:
cout <<"\n Salesperson Ki, put in Last Name: ";
cin >> salesrep[4].lname;
cout << "\n Enter Item#: ";
cin >> salesrep[4].itemnum;
cout <<"\n Enter Item Quantity";
cin >> salesrep[4].quantity;
break;
case Kee:
cout <<"\n Salesperon Kee, put in Last Name: ";
cin >> salesrep[5].lname;
cout << "\n Enter Item#: ";
cin >> salesrep[5].itemnum;
cout <<" \n Enter Item Quantity";
cin >> salesrep[5].quantity;
break;
case Niles:
cout <<"\n Salesperson Niles, put in Last Name";
cin >> salesrep[3].lname;
cout << "\n Enter Item#: ";
cin >> salesrep[3].itemnum;
cout <<"\n Enter Item Quantity";
cin >> salesrep[3].quantity;
break;
case Hamil:
cout << "\n Salesperson Hamil, put in Last Name";
cin >> salesrep[6].lname;
cout << "\n Enter Item#: ";
cin >> salesrep[6].itemnum;
cout <<"\n Enter Item Quantity";
cin >> salesrep[6].quantity;
break;
case Cams:
cout <<"\n Salesperson Cams, put in Last Name";
cin >> salesrep[7].lname;
cout << "\n Enter Item#: ";
cin >> salesrep[7].itemnum;
cout <<"Enter Item Quantity";
cin >> salesrep[7].quantity;
break;
case Tyson:
cout <<"\n Salesperson Tyson, put in Last Name";
cin >> salesrep[8].lname;
cout << "\n Enter Item#: ";
cin >> salesrep[8].itemnum;
cout <<"Enter Item Quantity";
cin >> salesrep[8].quantity;
break;
default: cout <<"\n ERROR: Imaginary Salesperson!";
}
}
return 0;
}
When I select 'Dixon' in as one of the switch values, my switch goes straight to default. I'm using toUpper() and placement() to verify that inputted names exist. How come when I input a name THAT DOES EXIST, it goes straight to default? I input the name exactly as its written in both enum and repname[].

Related

unable to enter number in output in c++

#include<iostream>
using namespace std;
int main()
{
int num1,num2,result;
cout << "enter num 1"<<endl;
cin >> num1;
cout << "enter num 2"<<endl;
cin >> num2;
result = num1 + num2;
cout << num1 <<"+" << num2 << " = "<< result;
return 0
}
this is the code I am unable to enter in output for adding the numbers
I wrote c++ code of adding two nums when output is given to enter 1st no then I am unable to write the no how can I write that output
The last sentence your code :"return 0",didn't write ";".

C++ Skips a line of output/input and goes straight to next input

string fullname, empid;
double hours, pay, fedrate, staterate, medicare = 1.5, socialtax = 6.2, overtime, overtimepay;
int option;
cout.precision(2);
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout << "Enter Employee's Full Name: " << endl;
cin >> fullname;
cout << "Enter Employee's ID: " << endl;
cin >> empid;
cout << "Enter Hours Worked: " << endl;
cin >> hours;
hours = fabs(hours);
cout << "Enter Pay Rate: " << endl;
cin >> pay;
pay = fabs(pay);
cout << "Enter Fed Tax Rate: " << endl;
cin >> fedrate;
fedrate = fabs(fedrate);
cout << "Enter State Tax Rate: " << endl;
cin >> staterate;
staterate = fabs(staterate);
After inputing a name for fullname it skips the employee id and goes straight into asking for hours worked. Do I have to use getline to fix that or did i do something wrong?
Yes. See here:
http://www.cplusplus.com/doc/tutorial/basic_io/
"However, cin extraction always considers spaces (whitespaces, tabs, new-line...) as terminating the value being extracted, and thus extracting a string means to always extract a single word, not a phrase or an entire sentence.
To get an entire line from cin, there exists a function, called getline, that takes the stream (cin) as first argument, and the string variable as second. For example:"

Printing out a Dynamic Arrays filled with pointers pointing to classes not printing out correct print function?

So, I have a homework problem with these steps:
1. Prompt the user for the number of people to create, then create an array of personType pointers to hold them.
Loop through the array, prompting the user to decide whether to create a personType,r studentType, and professorType and enter the data as necessary, then use appropriate new constructor.
Finally, loop through the array again and call the (virtual) print method for each person.
Delete the objects, deallocate the array and quit.
In this program, there are already 3 classes: personType, studentType, and professorType. studentType and professorType are derived from personType. Each of them has their own void print() function, with studentType and professorType print() funtions overriding personType print(). Yet, when I try to print, I can only seem to call personType print() method.
I have tried rewriting my code to use the constructors to populate each pointer in the array of pointers. I have also tried making personType print() method function protected, and adding a virtual print() method (though I don't think I fully understand virtual functions yet).
#include "personType.h"
#include "studentType.h"
#include "professorType.h"
int main()
{
int num;
personType **people;
string fName;
string lName;
string address;
double height;
string DOB;
char gender;
string id;
double gpa;
string classification;
string employeeID;
string department;
string degree;
int choice;
cout << "Please enter the amount of people you wish to create: ";
cin >> num;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '/n');
cout << "Please enter the amount of people you wish to create: ";
cin >> num;
}
people = new personType *[num];
system("pause");
system("cls");
for (int i = 0; i < num; i++) {
cout << "1 - Person, 2 - Student, and 3 - Professor" << endl;
cout << "Enter the type of person you wish to create: ";
cin >> choice;
while (cin.fail() && choice < 1 && choice > 3) {
cin.clear();
cin.ignore(256, '/n');
cout << "Enter the type of person you wish to create (1-3): ";
cin >> choice;
}
cout << "Person " << i + 1 << endl;
cout << "First Name: ";
cin >> fName;
cout << "Last Name: ";
cin >> lName;
cout << "Address: ";
cin.clear();
cin.ignore(1, '/n');
getline(cin, address);
cout << "Height (inches): ";
cin >> height;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '/n');
cout << "Height (inches): ";
cin >> height;
}
cout << "Date of Birth: ";
cin.clear();
cin.ignore(1, '/n');
getline(cin, DOB);
cout << "Gender: ";
cin >> gender;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '/n');
cout << "Gender: ";
cin >> gender;
}
if (choice == 2)
{
cout << "ID: ";
cin >> id;
cout << "Classification: ";
cin >> classification;
cout << "GPA: ";
cin >> gpa;
while (cin.fail()) {
cin.clear();
cin.ignore(1, '/n');
cout << "GPA: ";
cin >> gpa;
}
people[i] = new studentType(fName, lName, address, height, DOB, gender, gpa, classification, id);
}
else if (choice == 3)
{
people[i] = new professorType();
cout << "Employee ID: ";
cin.clear();
cin.ignore(1, '/n');
cin >> employeeID;
cout << "Department: ";
cin.clear();
cin.ignore(1, '/n');
getline(cin, department);
cout << "Degree: ";
cin.clear();
cin.ignore(1, '/n');
getline(cin, degree);
people[i] = new professorType(fName, lName, address, height, DOB, gender, employeeID, department, degree);
}
else {
people[i] = new personType(fName, lName, address, height, DOB, gender);
}
cout << endl;
}
system("cls");
for (int i = 0; i < num; i++) {
people[i]->print();
cout << endl;
}
for (int i = 0; i < num; i++)
delete people[i];
delete[] people;
}
I can only print from the personType print function, instead of calling studentType and professor type print functions when needed.

Why won't the string cout

O.F community! I'm very new to c++ and I decided to create my own game.
My issue is that at one point in the game the player is asked to answer 3 things:
-Gender
-Age
-Setting
void assessment()
{
cout << "Now that the characteristics have been selected. Let's review what they are:\n\n";
cout << "Press any key to continue\n\n";
cin >> anykey;
cout << "You are a " << ageNumber << " year old " << gender; //incomplete - needs //<< setting;
}
The issue is with gender not being displayed. It can cout << ageNumber fine. But when the game is played and this part is reached this is what it says:
Now that the characteristics have been selected. Let's review what they are:
Press any key to continue
1
You are a 16(that is what I put for ageNumber earlier on) year old . <- Notice how "old" and "." have a space? As if the string gender is read as a blank.
EDIT: It is supposed to say:
You are a 16 year old male/female/it.
This is the part that determines the gender.
void fate()
{
cout << "Before we begin, a few characteristics must be selected\n\n";
cout << "Gender?\n\n";
cout << "1. Male\n";
cout << "2. Female\n";
cout << "3. Other\n\n";
cin >> genderNumber;
cout << "Now your next characteristic...Press any key to continue\n\n";
cin >> anykey;
cout << "What is your age? (Must be younger than 50 to play)\n\n";
cin >> ageNumber;
setting2();
if (genderNumber == 1)
{
string gender = "male";
}
else if (genderNumber == 2)
{
string gender = "female";
}
else if (genderNumber == 3)
{
string gender = "'it'";
}
else
{
"invalid input\n\n\n\n\n\n";
fate();
}
===========================================================================================
This is the full code:
#include <iostream>
#include <string>
using namespace std;
void rules();
void controls();
void start();
void fate();
void assessment();
void setting2();
int fateNumber;
int anykey;
int ageNumber;
int settingNumber;
int genderNumber;
string gender;
string setting;
int main(int argc, char** argv)
{
cout << "===W E L C O M E T O C H O O S E Y O U R F A T E=== \n\n";
cout << "Press any key to continue\n";
cin >> anykey;
start();
}
void controls()
{
cout << "Throughout this game will you be making choices, each choice will have a corresponding number next to it. Press the letter to the corresponding choice you want to make. Press any key to continue\n";
cin >> anykey;
cout << "Here is an example...you are a cat, you can either\n\n";
cout << "1. Meow\n\n";
cout << "2. Hiss\n";
cout << "Press any key to continue\n";
cin >> anykey;
cout << "If I wanted to Hiss I would press the 2 key\n\n";
cout << "Press any key to continue on to the rules\n\n";
cin >> anykey;
rules();
}
void rules()
{
cout << "#1 You will be given a set number of choices. Press any key to continue\n\n";
cin >> anykey;
cout << "#2: There are 2 factors to this game. Press any key to continue\n\n";
cin >> anykey;
cout << "#3: The first factor is that either you live or you die. Press any key to continue\n\n";
cin >> anykey;
cout << "#4: The second factor is that if you live, your character will be judged based on events you've made. You can still live, but you might have a good or bad effect on the people around you. Press any key to continue\n\n";
cin >> anykey;
cout << "Let's play shall we?";
}
void start()
{
cout << "You shall begin a journey that'll decide either you make it or you don't. Press any key to continue\n\n";
cin >> fateNumber;
cout << "But before we start...The game needs to be explained.\n\n\n\n";
cout << "Controls(1 key)---------------------------Rules(2 key)---------------Skip(3 key) \n\n";
cin >> fateNumber;
if (fateNumber == 1)
{
controls();
}
else if (fateNumber == 2)
{
rules();
}
else if (fateNumber == 3)
{
fate();
}
else
{
cout << "invalid key\n\n\n\n\n\n\n";
start();
}
}
void fate()
{
cout << "Before we begin, a few characteristics must be selected\n\n";
cout << "Gender?\n\n";
cout << "1. Male\n";
cout << "2. Female\n";
cout << "3. Other\n\n";
cin >> genderNumber;
cout << "Now your next characteristic...Press any key to continue\n\n";
cin >> anykey;
cout << "What is your age? (Must be younger than 50 to play)\n\n";
cin >> ageNumber;
setting2();
if (genderNumber == 1)
{
string gender = "male";
}
else if (genderNumber == 2)
{
string gender = "female";
}
else if (genderNumber == 3)
{
string gender = "'it'";
}
else
{
"invalid input\n\n\n\n\n\n";
fate();
}
if (ageNumber >= 50 && ageNumber < 100)
{
cout << "Didn't you read the age rating dumbass? Younger than 50...\n\n";
}
else if (ageNumber < 50 && ageNumber > 22)
{
setting2();
}
else if (ageNumber <= 22 && ageNumber >= 16)
{
setting2();
}
else if (ageNumber < 16 && ageNumber >= 0)
{
setting2();
}
else if (ageNumber >= 100)
{
cout << "More than a century old and you expect me to believe you got this far? Bullshit.";
}
else
{
cout << "Error - Invalid number\n\n\n\n\n\n";
cout << "what is your age again?\n\n";
cin >> ageNumber;
}
}
void assessment()
{
cout << "Now that the characteristics have been selected. Let's review what they are:\n\n";
cout << "Press any key to continue\n\n";
cin >> anykey;
cout << "You are a " << ageNumber << " year old " << gender << ". You are " << setting << endl << endl;
if (settingNumber == 1)
{
string setting = "home";
}
else if (settingNumber == 2)
{
string setting = "jail";
}
}
void setting2()
{
cout << "Alright and lastly pick your setting\n\n";
cout << "1. Home sweet home\n";
cout << "2. Vacation \n";
cout << "3. Jail\n\n";
cin >> settingNumber;
assessment();
}
=======================================================================================
Any help is appreciated ^^ Code on!
Output (thru ofstream-s like cout) is buffered in C++. You want
cout << flush;
or
cout << endl;
to ask the buffer to be flushed (endl manipulator also emits a new line but flush does not).
So code:
cout << "You are a " << ageNumber << " year old " << gender << flush;
or
cout << "You are a " << ageNumber << " year old " << gender << endl;
Also, your gender should be declared at a wider scope:
if (genderNumber == 1) {
string gender = "male";
}
should become (to refer to the global gender)
if (genderNumber == 1) {
gender = "male";
}
BTW, if you enabled all warnings with your compiler (e.g. compile with g++ -g -Wall -Wextra, if using GCC, e.g. on Linux) you should have been warned. And of course, you should use the debugger (e.g. gdb, at least on Linux) and step into your code with it.

How to make the script rerun?

I know this is very vague but im new to C++. Im making a calculator as a first time project, and what im wanting to do is, if replied to with 'y', make the script rerun from the beginning...basically.
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
int main()
{
cout << "Hello and Welcome to the Test Calculator!\n";
signed char choice;
char resp;
cout << "Choose your problem:\n a)Addition\n b)Subtraction\n c)Multiplication\n d)Division\n e)Square Root\n f)Hypotenuse\n";
scanf ("%c", &choice);
switch (choice)
{
case 'a':
{
int a;
int b;
cout << "Addition\n";
cout << "Please enter a number:\n";
cin >> a;
cout << "Please enter your second number:\n";
cin >> b;
cin.ignore();
int result = a + b;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result;
cin.get();
break;
}
case 'b':
{
int c;
int d;
cout << "Subtraction\n";
cout << "Please enter a number:\n";
cin >> c;
cout << "Please enter your second number:\n";
cin >> d;
cin.ignore();
int result2 = c - d;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result2;
cin.get();
break;
}
case 'c':
{
int e;
int f;
cout << "Multiplication\n";
cout << "Please enter a number:\n";
cin >> e;
cout << "Please enter your second number:\n";
cin >> f;
cin.ignore();
int result3 = e * f;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result3;
cin.get();
break;
}
case 'd':
{
int g;
int h;
cout << "Division\n";
cout << "Please enter a number:\n";
cin >> g;
cout << "Please enter your second number:\n";
cin >> h;
cin.ignore();
int result4 = g / h;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result4;
cin.get();
break;
}
case 'e':
{
int x;
#define square ((x)*(x))
cout << "Square Root\n";
cout << "Please enter a number:\n";
cin >> x;
cin.ignore();
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<square;
cin.get();
break;
}
case 'f':
{
int i;
int j;
cout << "Hypotenuse\n";
cout << "Enter your smaller side:\n";
cin >> i;
cout << "Please enter the longer side:\n";
cin >> j;
cin.get();
int hypotenuse = ((i*i)+(j*j));
cout << "Calculating...\n";
cout << "The hypotenuse is the square root of:\n"<<" "<<hypotenuse;
cin.ignore();
cout << "Would you like to do another problem?\n y)Yes\n n)No\n";
cin >> resp; //this is where im trying to test this at
}
default:
{
cout << " \n";
cout << "Error: Undefined response\n";
cout << "Contact the source programmer for details\n";
}
}
}
If you put the switch into a while loop that checks to see if the char == 'n' it will continue until it finds it.
while(choice != 'n')
{
switch (choice)
{
case 'a':
{
int a;
int b;
cout << "Addition\n";
cout << "Please enter a number:\n";
cin >> a;
cout << "Please enter your second number:\n";
cin >> b;
cin.ignore();
int result = a + b;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result;
cin.get();
break;
}
case 'b':
{
int c;
int d;
cout << "Subtraction\n";
cout << "Please enter a number:\n";
cin >> c;
cout << "Please enter your second number:\n";
cin >> d;
cin.ignore();
int result2 = c - d;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result2;
cin.get();
break;
}
case 'c':
{
int e;
int f;
cout << "Multiplication\n";
cout << "Please enter a number:\n";
cin >> e;
cout << "Please enter your second number:\n";
cin >> f;
cin.ignore();
int result3 = e * f;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result3;
cin.get();
break;
}
case 'd':
{
int g;
int h;
cout << "Division\n";
cout << "Please enter a number:\n";
cin >> g;
cout << "Please enter your second number:\n";
cin >> h;
cin.ignore();
int result4 = g / h;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result4;
cin.get();
break;
}
case 'e':
{
int x;
#define square ((x)*(x))
cout << "Square Root\n";
cout << "Please enter a number:\n";
cin >> x;
cin.ignore();
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<square;
cin.get();
break;
}
case 'f':
{
int i;
int j;
cout << "Hypotenuse\n";
cout << "Enter your smaller side:\n";
cin >> i;
cout << "Please enter the longer side:\n";
cin >> j;
cin.get();
int hypotenuse = ((i*i)+(j*j));
cout << "Calculating...\n";
cout << "The hypotenuse is the square root of:\n"<<" "<<hypotenuse;
cin.ignore();
cout << "Would you like to do another problem?\n y)Yes\n n)No\n";
cin >> choice; //this is where im trying to test this at
}
}
}
You can add another option to continue calculator. something like this:
while(doContinue == true){
switch{.....}
}
that is, enclose the switching part of code in a while loop. Set doContinue as true at first then change it at the end according to the user input.

Resources