Allowing User input to change function parameters C++ - c++

I just began learning C++ this week, and I'm at a very basic learning stage.
I'm using a switch and attempting to let the user input the parameters of the function getDayOfWeek, and then call it to have it carry out the function based on the entered parameters. Any help? Below I have tried cin >> getDayofWeek() but truthfully I have no clue!
Thanks!
#include <iostream>
using namespace std;
string getDayOfWeek(int dayNum){
string dayName;
switch(dayNum){
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "invalid day number";
}
return dayName;
}
int main()
{
cin >> getDayOfWeek();
return 0;
}

First, you need to read the input into a variable:
int day;
cin >> day;
And now, you have a very convenient variable that you can pass to your function:
cout << getDayOfWeek(day);

You could create an array holding the day names instead of switching over the input, and the cin >> needs a variable. Currently you are putting the user input into the variable returned by the function !
#include <iostream>
using namespace std;
string getDayOfWeek(int dayNum) {
string weekdays [7] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
if (dayNum < 0 || dayNum > 6) {
return string("invalid day number");
} else {
return weekdays[dayNum];
}
}
int main() {
int dayNum;
cin >> dayNum;
weekday = getDayOfWeek(dayNum);
return 0;
}

Related

Loop control inside void function keeps looping

void getDay() {
bool repeat;
do
{
cout << "Enter the day code (first 2 letters): ";
cin >> weekDay1;
cin >> weekDay2;
weekDay1 = toupper(weekDay1);
weekDay2 = toupper(weekDay2);
switch (weekDay1)
{
case 'M':
break;
case 'T':
break;
case 'W':
break;
case 'F':
break;
case 'S':
break;
default:
cout << "Invalid input. Please try again.\n";
repeat = true;
break;
}
switch (weekDay2)
{
case 'O':
break;
case 'U':
break;
case 'E':
break;
case 'H':
break;
case 'R':
break;
case 'A':
break;
default:
cout << "Invalid input. Please try again.\n";
repeat = true;
break;
}
}while (repeat == true);
return;
}
I need this function to run once, and loop if the input is not one of the accepted characters. I'm trying to prevent any bad input, but it loops infinitely if the input entered on the initial run is not accepted. It works fine if the input is good on the first run, but I keep getting run-time errors for not initializing bools and I need some help adjusting this control.
The condition in the while loop is always true because you never set it to false in its body. You can do something like this:
void getDay() {
// Initializing while declaring is a good practice.
bool repeat = false;
do {
.
.
repeat = false;
.
switch(...) {
...
}
} while (repeat);
}
Now, repeat = true is only called if one of the switch statements invokes default.

Switch statement (string) keeps selecting default value unless its zero

Switch statement only works when I change the value between the brackets to 0 in cout << getDayOfWeek(0);.
Any number between 1-6 selects the default value "Invalid Day Number".
There isn't any issues (no issues found).
I tried retyping it from scratch and nothing worked.
The code is supposed to print out the day when I enter its number, but it only works with 0. If I put other numbers, it selects the default value.
#include <iostream>
#include <cmath>
#include <string>
#include <cstring>
using namespace std;
string getDayOfWeek(int dayNum) {
string dayName;
switch (dayNum) {
case 0:
dayName = "Sunday";
break;
switch (dayNum)
case 1:
dayName = "Monday";
break;
switch (dayNum)
case 2:
dayName = "Tuesday";
break;
switch (dayNum)
case 3:
dayName = "Wednesday";
break;
switch (dayNum)
case 4:
dayName = "Thursday";
break;
switch (dayNum)
case 5:
dayName = "Friday";
break;
switch (dayNum)
case 6:
dayName = "Saturday";
break;
default:
dayName = "Invalid Day Number";
}
return dayName;
}
int main()
{
cout << getDayOfWeek(5);
return 0;
}
You're using the switch statement incorrectly. The code should look like this:
switch(dayNum){
case 0:
// do something
break;
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
case 4:
// do something
break;
case 5:
// do something
break;
case 6:
// do something
break;
default:
// do something
break;
}
You shouldn't repeat the switch statement over and over again; just keep the first one.
You won't need switch (dayNum) inside the switch statement.
They will create nested switch statements and leave only case 0 and default in the first switch statement.
Try this:
#include <iostream>
#include <cmath>
#include <string>
#include <cstring>
using namespace std;
string getDayOfWeek(int dayNum) {
string dayName;
switch (dayNum) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Invalid Day Number";
}
return dayName;
}
int main()
{
cout << getDayOfWeek(5);
return 0;
}
You could avoid the switch statement by using an array:
static const char day_names[] =
{
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
const std::string day_of_week = day_names[dayNum];
The switch statement adds more lines of code to your project, which increases complexity and the probability of defects.

Using The Result From An If Statement To Execute A Switch Cases?

I'm not sure if this will work. I'm assuming it should , I just can't figure out how.
I am trying to execute a Switch case from the result from an If Statement.
For example if the result from the If is 1 , the first case executes
This is what I'm thinking:
#include <iostream>
#include <ctype.h>
using namespace std;
int main(){
cout<<"\tDetermine what has been inputted"<<endl<<endl;
char value,ch;
int option;
do{
cout<<"Input something: ";
value = islower(value);
cin>>value;
if(value>='0' && value<='0'){
option == 1;
}
else if (value=='a' || value=='e' || value=='i' ||value=='o' ||
value=='u') {
option ==2;
}
switch(option){
case 1:
cout<<"You entered "<<value <<" a digit."<<endl;
cout<<"Do you wish to test again? (Y/N): "<<endl;
cout<<"Do you wish to test again? (Y/N): "<<endl;
cin>>ch;
break;
case 2:
cout<<"You have entered"<<value<<" a vowel"<<endl;
cout<<"Do you wish to test again? (Y/N): "<<endl;
cin>>ch;
break;
default:
cout<<"That input is not valid"<<endl;
}
} while (ch == 'y' || ch =='Y');
return 0;
}
Is what I'm thinking possible?
Intialize variables to avoid UB:
char value,ch = 0;
int option = 0;
this is true only if value is '0':
if(value>='0' && value<='0')
you have two typos: == instead of =
option = 1;
and
option = 2;
You might want to set ch to 'Y' in case of invalid output?
default:
cout<<"That input is not valid"<<endl;

c++ While Loop termination with function

scratching my head on this as it was working just fine earlier but when I went to add some other functions suddenly my program freaked out and I can not get it back to what it was.
class has me writing a rock/paper/scissors program to go up against a computer, any help with why the loop keeps terminating itself would be wonderful
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void RPSout(char);
int RPScomp();
int main() {
char choice;
int endit=0;
while (endit == 0)
{
cout << "\n\n\tReady to play Rock/Paper/Scissors against the computer??(please choose R/P/S)(Q to quit)\n";
cin >> choice;
RPSout(choice);
if (choice=='Q'||'q')
{endit=1;}
}
return 0;
}
void RPSout(char choose)
{
int RPS =0;
int comp=0;
switch (choose)
{
case 'R':
case 'r':
{
cout <<"Your choice: Rock";
break;
}
case 'P':
case 'p':
{
cout <<"Your choice: Paper";
break;
}
case 'S':
case 's':
{
cout << "Your choice: Scissors";
break;
}
case 'Q':
case 'q':
{
cout << "Bye Bye Bye";
break;
}
default:
cout<<"You enter nothing!"<<endl;
cout << "The valid choices are R/P/S/Q)";
}
return;
}
int RPScomp()
{
int comp=0;
const int MIN_VALUE =1;
const int MAX_VALUE =3;
unsigned seed = time(0);
srand(seed);
comp =(rand() % (MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
return comp;
}
if (choice=='Q'||'q')
This is equivalent to
if ((choice == 'Q') || 'q')
Which is almost certainly not what you want. 'q' is a non-zero char literal, which is "truthy" and so this expression will never be false. It's akin to writing if (choice == 'Q' || true).
The solution is:
if (choice=='Q' || choice=='q')
The statement
if (choice=='Q'||'q')
always tests true and therefore sets your flag to terminate the loop.
Try:
if (choice=='Q'||choice=='q')
I think your if statement should be if (choice=='Q'|| choice=='q')
Your issue if with the if statement
if (choice=='Q'||'q')
{endit=1;}
the || 'q' part will always be true since 'q' in ASCII is not 0
Change your code to
if (choice=='Q'|| choice=='q')
{endit=1;}

A few coding convention/standard practice questions

I have this function that takes a string from main. The string contains all of the valid characters that a user can input from some menu options. Function will put character input into a variable and be compared to each character of the string. Compare input variable to the string characters until valid input is entered.
My question is, what is the best way to implement this loop? I don't like using while (true) with a return in the middle because it looks like an infinite loop with an exception in the middle, which makes it slightly harder to read, but I'm not sure how else I can do what I want it to do. What's the best practice for achieving my goal? Thanks.
char getValidKey(string validKeys)
{
char letter;
while (true) {
cout << "Operation ? ";
cin >> letter;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int i = 0; i < validKeys.length(); i++) {
if (letter == validKeys[i])
return letter;
}
cout << "Error. Invalid input.\n";
}
}
Also, I have a switch statement with multiple returns. Is it more common/preferred to assign calculations to a variable and have one return at the end or is this way generally okay?
string opStr;
switch (myOperation) {
case 1:
opStr = "RIGHT";
break;
case 2:
opStr = "LEFT";
break;
case 3:
opStr = "CENTER_ONLY";
break;
case 4:
opStr = "CENTER_MISSING";
break;
default:
opStr = "Error. Invalid input.";
break;
}
return opStr;
OR
switch (myOperation) {
case 1:
return "RIGHT";
break;
case 2:
return "LEFT";
break;
case 3:
return "CENTER_ONLY";
break;
case 4:
return "CENTER_MISSING";
break;
default:
return "Error. Invalid input.";
break;
}
For the first case, refactor your code in smaller self-contained functions, and it becomes clear to understand the logic of getValidKey even from a while(true):
char isKeyValid(char x, const string& validKeys)
{
return validKeys.find(x) != string::npos;
}
char readCharFromCin()
{
char letter;
cout << "Operation ? ";
cin >> letter;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return letter;
}
char getValidKey(const string& validKeys)
{
while (true)
{
const char key = readCharFromCin();
if(isKeyValid(key, validKeys)) return letter;
cout << "Error. Invalid input.\n";
}
}
For the second case, avoid break and simply return from your switch. Make the function containing the switch only do one thing.
string switchOperation(int myOperation)
{
switch (myOperation)
{
case 1: return "RIGHT";
case 2: return "LEFT";
case 3: return "CENTER_ONLY";
case 4: return "CENTER_MISSING";
}
return "Error. Invalid input.";
}
Also, try to maximize usage of const and pass string instances you're only reading by const& to avoid unnecessary copies.