Switches in C++ - c++

I am new to C++ and programming in general and was trying to figure out a way to create a switch in C++ to trigger when a number entered is divisible by 3, by 5, and by both 3 and 5. Here is what I have so far:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number;
cout << "Please input a number and then press the enter key" << endl;
cin >> number;
switch (number){
case "/3":
cout << "Fizz" << endl;
break;
case "/5":
cout << "Buzz" << endl;
break;
case "/3" "/5":
cout << "FizzBuzz" << endl;
break;
default:
cout << "Please select another number." << endl;
}
}
Any help with this would be greatly appreciated! :)

In C++ the switch labels must be compile-time evaluable constant expressions that are integral types.
"/3", for example, is a string literal and so does not fit that requirement.
In this case, use number % 3 == 0 to test for divisibility by 3, and so on and use an if, else block:
if (number % 15 == 0){
/*FizzBuzz - do this one first as my `if` block is not mutually exclusive*/
} else if (number % 3 == 0){
/*Fizz*/
} else if (number % 5 == 0){
/*Buzz*/
}

You can use if else.
int remainder1 = 0, remainder2 = 0;
remainder1 = number % 3;
remainder2 = number % 5;
if(remainder1 == 0 && remainder2 ==0) // both
cout<<"FizzBuzz"<<'\n';
else if(remainder1 == 0) // number can be divided by 3
cout<<"Fizz"<<'\n';
else if(remainder2 == 0) // number can be divided by 5
cout<<"Buzz\n";
else // neither
cout<<"......"<<'\n';
BTW, you do have to read the basic book about C++.
here, you can know more about switch

If you really want to do with switch, here is a method, but is not nice. The easiest way is how Bathsheba said.
#include <iostream>
#include <cmath>
using namespace std;
enum class divided { DivideBy3 , DivideBy5 , DivideBy3and5 }; // "strong enum"
// enum class divided { DivideBy3 , DivideBy5 , DivideBy3and5 }; //also good but can be unsafe
divided getCase(int number)
{
divided div;
if(number%3 == 0)
div = divided::DivideBy3;
if(number%5 == 0)
div = divided::DivideBy5;
if(number%3 ==0 && number%5 == 0)
div = divided::DivideBy3and5;
return div;
}
int main()
{
int numberIn;
cout << "Please input a number and then press the enter key" << endl;
cin >> numberIn;
divided number = getCase(numberIn);
switch (number)
{
case divided::DivideBy3:
cout << "Fizz" << endl;
break;
case divided::DivideBy5:
cout << "Buzz" << endl;
break;
case divided::DivideBy3and5:
cout << "FizzBuzz" << endl;
break;
default:
cout << "Please select another number." << endl;
}
}
look at this for enum vs class enum. Keep going.

Related

expected unqualified id before return 0

I'm new to C++. I have errors. But, i dont know how to fix it. Could anyone please help me? Thank you.
P - Print numbers
A - Add a number
M - Display mean of the numbers
S - Display the smallest number
L - Display the largest number
Q - Quit
Errors : expected unqualified id before return 0
error : expected ';' before {}
#include <iostream>
#include <vector>
using namespace std;
int main(){
char input {};
vector <double> numbers {};
int number{};
int sum{};
int min_number{};
int max_number{};
bool condition {true};
cout << "Enter a command" << endl;
cin >> input;
if(numbers.size() > 0){
while(condition){
if (input == 'P' || input == 'p'){
for(auto x: numbers)
cout << x << endl;
}
else if(input == 'A' || input == 'a'){
cout << "Enter a number";
cin >> number;
numbers.push_back(number);
}
else if(input == 'M' || input == 'm'){
for(auto x : numbers)
sum += x;
cout << sum / numbers.size() << endl;
}
else if(input =='S' || input == 's'){
for(size_t i {0}; i < numbers.size(); ++i)
if(numbers.at(i) < min_number)
min_number =numbers.at(i);
}
else if(input =='L' || input == 'l'){
for(size_t i {0}; i < numbers.size(); ++i)
if(numbers.at(i) > max_number)
max_number =numbers.at(i);
}
else if(input =='Q' || input == 'q'){
condition {false};
}
}
cout << "[] - list is empty, unable to calculate" << endl;
}
return 0;
}
In your section dealing with Q/q, the statement:
condition {false};
is not a valid form of assignment, you should instead use:
condition = false;
The braces are fine for initialisation, but that's not what you're trying to do on that line.
As an aside, this line:
if(numbers.size() > 0){
seems a little strange. Since you initialise the list to empty, the main loop will never start (because it's inside the if block) even though you have already asked the user for input.
That's a runtime error rather than a syntax error but you'll still need to fix it at some point.
I suspect that particular should should be done only as part of the calculation of the mean, so as to avoid dividing by zero.
I have written this for you. Since, you're a learner, I think that you should be practicing better things like STL functions and not using using namespace std; at top.
You may find some things new, but don't be frightened, just search them on some website like cppreference and see what that entity do and how to effectively use it.
There were many logical errors. #paxdiablo has mentioned them in his answer. I have removed every of them and this code works.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <vector>
int main() {
std::vector<double> numbers;
while (true) {
char input;
std::cout << "Enter a command: ";
std::cin >> input;
switch (std::toupper(input)) {
case 'P':
if (numbers.empty())
std::cerr << "The list is empty!" << std::endl;
else {
for (auto &&i : numbers)
std::cout << i << ' ';
std::cout << std::endl;
}
break;
case 'A': {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
numbers.push_back(number);
break;
}
case 'M':
if (numbers.empty())
std::cerr << "The list is empty! Cannot perform the operation!!";
else {
int sum = 0;
for (auto &&i : numbers)
sum += i;
std::cout << "Mean: " << (sum / numbers.size()) << std::endl;
}
break;
case 'S':
std::cout << "Smallest Number: " << *std::min_element(numbers.begin(), numbers.end()) << std::endl;
break;
case 'L':
std::cout << "Largest Number: " << *std::max_element(numbers.begin(), numbers.end()) << std::endl;
break;
case 'Q':
return 0;
default:
std::cerr << "Unrecognised Command!!" << std::endl;
}
}
return 0;
}

Returning the output of a function as the return code of main()

I'm self-teaching myself here so I don't have a model answer available.
Working through program flow examples and trying to get a number guesser based on binary searching. I've got it to run and catch edge cases successfully but one objective is to have main() return the number of guesses made. I refactored the main code into a separate function to make it clearer, but I can't get the return code correct, I suspect it's to do with variable scope but can't figure it out.
#include <iostream>
using namespace std;
int guessNumber(int highest, int lowest, int lAttempts)
{
int guess = lowest + ((highest - lowest) * 0.5);
char response = 'a';
lAttempts++;
cout << "My guess is " << guess << ", am I correct?" << endl;
cout << "(y)es/too (h)igh/too (l)ow/(q)uit" << endl;
cin >> response;
while (response != 'y' && response != 'h' && response != 'l' && response != 'q')
{
cout << "I'm sorry, I didn't understand that" << endl;
cout << "(y)es/too (h)igh/too (l)ow/(q)uit" << endl;
cin >> response;
}
switch (response)
{
case 'y':
cout << "I guessed correctly after " << lAttempts << " attempts";
break;
case 'h':
highest = guess;
guessNumber(highest, lowest, lAttempts);
break;
case 'l':
lowest = guess;
guessNumber(highest, lowest, lAttempts);
break;
case 'q':
cout << "Exiting program";
break;
}
return lAttempts;
}
int main()
{
cout << "Think of a number between 1-100" << endl;
int highest = 100;
int lowest = 0;
int attempts = 0;
attempts = attempts + guessNumber(highest, lowest, attempts);
return attempts;
}
cout returns the correct number of attempts but the program (so main()) always exits with 1.
What am I missing here?
Thanks.
You're missing to update your attempt variable within your switch statements.
It should be like this.
lAttempts = guessNumber(highest, lowest, lAttempts);

How can I clean this code up by using a loop?

Basically, this program allows a user to enter a sentence and depending on the users selection, it will show the middle character of the sentence, display it uppercase or lowercase, or backwards. Simple program, but I am new to programming so that may be the problem. I would like to figure out how to use loops instead of a ton of if statements. When I try to make some loops it breaks certain parts of the code but I am sure that is because I don't properly understand them. If you have any criticism or any advice on the code, I'd be happy to hear it. Thanks in advance!
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int sel;
string sent;
bool validinput;
int i;
int x;
int j;
int a;
cout << "Welcome to my program. Enter a sentence and select one of the options below.\n";
cout << "Enter -999 to exit the program." << endl;
cout << "============================================================================" << endl;
cout << endl;
cout << "1. Display the middle character if there is one." << endl;
cout << "2. Convert to uppercase." << endl;
cout << "3. Convert to lowercase." << endl;
cout << "4. Display backwards." << endl;
cout << "Enter a sentence: ";
getline (cin, sent);
cout << "Selection: ";
cin >> sel;
if (sel < 1 && sel > 4)
{
cout << "Invalid input. Try again. Selection: ";
cin >> sel;
validinput = false;
}
else (sel >= 1 && sel <= 4);
{
validinput = true;
}
if (validinput == true)
{
if (sel == 1)
{
j = sent.length() / 2;
cout << "The middle character is: " << sent.at(j) << endl;
}
if (sel == 2)
{
for (int i = 0; i < sent.length(); i++)
{
if (sent.at(i) >= 'a' && sent.at(i) <= 'z')
{
sent.at(i) = sent.at(i) - 'a' + 'A';
}
}
cout << "Uppercase: " << sent << endl;
}
if (sel == 3)
{
for (int x = 0; x < sent.length(); x++)
{
if (sent.at(x) >= 'A' && sent.at(x) <= 'Z')
{
sent.at(x) = sent.at(x) - 'A' + 'a';
}
}
cout << "Lowercase: " << sent << endl;
}
if (sel == 4)
{
for (a = sent.length() - 1; a >= 0; a--)
{
cout << sent.at(a);
}
}
}
system("pause");
return 0;
}
Personally I would use the switch selection statement. I roughly did this just to explain a bit on how it can make your code more friendly and understandable.
int sel;
bool validInput = false;
switch(sel)
{
case 1:
//display middle char if there's one
case 2:
//convert to uppercase
case 3:
//convert to lowercase
case 4:
//display backwards
validInput = true;
break;
default: //if number does not meat 1, 2, 3 or 4
validInput = false;
break;
}
As you may notice, for case 1, case 2, case 3 and case 4, there's a break just to say that if the number is between 1 to 4; validInput is true.
Reference: Switch Selection Statement
i suggest using a switch. It will organize your code better. From looking at your code you seem to have used for and if wisely. But I suggest the if statements checking for the input be replaced with switch.

Redefiniton of an int error

I'm teaching my self C++ on the side and i realize this question may seem remedial to some. In the game I'm making as part of the learning process I want the user to be able to pick a difficulty and when they pick one or the other the random number value range changes. The compiler I'm using is x-Code by the way. Here is the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
int secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
int secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
int secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
The 2 errors occur in case 2 and 3 where i try to redefine the value of secretNumber.
The case blocks do not open different scopes, but are rather part of the same block. Your code (considering only scopes) looks somehow similar to:
int secretNumber;
{
int secretNumber = rand() % 10 + 1;
...
int secretNumber = rand() % 50 + 1;
...
int secretNumber = rand() % 100 + 1;
}
Three different variables with the same name are being declared in the same scope, which is not allowed in the language. Note that all three declarations inside the switch would also hide the variable declared in the outer scope, which is probably not what you want anyway.
It looks like you have some background in some other languages - perhaps a functional language and perhaps some JavaScript.
One of the key features of C++ is scoping. Variables (named value holders) have a lifetime of the scope they are within, and variables are only visible within the scope they are defined. (Not to be confused with objects, which through pointers and allocation can be teased off the stack and into heap memory, only to be lost when the variables with their address go out of scope if they are not properly deallocated).
{
int i = 1;
}
std::cout << "i is " << i << std::endl; // compiler error, i does not exist here.
void foo() {
int i = 1;
}
void bar() {
foo();
std::cout << i << std::endl; // compiler error, i does not exist here.
}
Also, unless decorated as "const", C++ variables are mutable - they can be changed.
int i = 1;
i = 2;
std::cout << i << std::endl; // writes 2, not 1.
So: your code is not 'redefining' secretNumber, it is shadowing the previous definition, hiding it for the duration of the current scope. Thus when you assign a value to the inner version, the "secretNumber" visible to code outside the scope is untouched.
#include <iostream>
int main()
{
int foo = 1; // outer foo
std::cout << "Originally, foo = " << foo << std::endl;
{
int foo = 2; // inner foo
std::cout << "Inside the inner scope, foo = " << foo << std::endl;
}
// inner foo doesn't exist here, so it references outer foo.
std::cout << "But the original foo still exists, " << foo << std::endl;
}
What you actually want to do is simply assign a new value to the original secretNumber variable you declared in the outer scope, since that is the only variable named "secretNumber" available to code in that scope.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
This is one reason why many C++ programmers choose to use prefix and suffix notations to distinguish certain types of variables:
#include <iostream>
class Foo {
public:
int m_i; // member variable, m_xxx
Foo(int); // constructor taking an int.
};
static int s_i;
Foo::Foo(int i_) // arguments use _ suffix
{
int i = i_; // local value of i
i *= 3;
m_i = i; // we're assigning it the local value, not the argument.
}
int main()
{
int i = 1;
Foo foo(2);
s_i = 3;
std::cout << "i = "<<i<<", foo.m_i = "<<foo.m_i<<", s_i = "<<s_i<< std::endl;
}
Live Demo: http://ideone.com/dSTwPT
You are getting the compile time error because you are redeclaring the same variable within the same scope (case statement block level scope). You need to delete int before secretNumber in all the case statements. Doing otherwise, the secretNumber variable declared at the while loop block level will stay undefined.

C++ functions and random number

When I write this code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int random = std::rand() % 9 + 1;
int main()
{
std::srand(std::time(0));
if(random==1 || random ==2 || random == 3){
cout << "Wolf" << endl;
} else if(random==4 || random ==5 || random == 6){
cout << "Bear" << endl;
} else if(random==7 || random ==8 || random == 9){
cout << "Pig" << endl;
}
}
Every time I run it I get something else printed(Wolf, Pig or Bear), like I wanted.
But when I add this function in my code like this:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int random = std::rand() % 9 + 1;
void func(){
if(random==1 || random ==2 || random == 3){
cout << "Wolff" << endl;
} else if(random==4 || random ==5 || random == 6){
cout << "Bearr" << endl;
} else if(random==7 || random ==8 || random == 9){
cout << "Pigg" << endl;
}
}
int main()
{
std::srand(std::time(0));
if(random==1 || random ==2 || random == 3){
cout << "Wolf" << endl;
func();
} else if(random==4 || random ==5 || random == 6){
cout << "Bear" << endl;
func();
} else if(random==7 || random ==8 || random == 9){
cout << "Pig" << endl;
func();
}
}
I want every time I run it to get printed something else like Bear Bearr, Wolf Wolff or Pig Pigg.But with this function whenever I run it I get the same result.What is the problem?
Please help me, I'm new in C++.
The global initializers are executed before main is called. So you never reseed your PRNG, and thus always draw the same "random" numbers.
That said, I don't believe that either of your code pieces produce different output with each run, since they have the same initialization order problem.
EDIT: Changing to match your stated goal of "bear", "bearr", "pig", "pigg".
int random = std::rand() % 9 + 1;
declares a global variable called "random" which is assigned a value during startup, before main(). The value will be the (default return value of rand() modulo'd by 9) plus one. It does not automatically change.
What you appear to be looking for is
int random()
{
return (std::rand() % 9) + 1;
}
which defines a function that calls rand, modulos the value by 9 and then returns one. EDIT: To see the same value inside the "func()" function, pass it by value or reference as a function parameter:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::endl;
int random() {
return (std::rand() % 9) + 1;
}
void func(int randNo){
switch (randNo) {
case 1: case 2: case 3:
cout << "Wolff" << endl;
break;
case 4: case 5: case 6:
cout << "Bearr" << endl;
break;
case 7: case 8: case 9:
cout << "Pigg" << endl;
break;
}
}
int main()
{
std::srand(std::time(0));
int randNo = random();
switch (randNo) {
case 1: case 2: case 3:
cout << "Wolf" << endl;
func(randNo);
break;
case 4: case 5: case 6:
cout << "Bear" << endl;
func(randNo);
break;
case 7: case 8: case 9:
cout << "Pig" << endl;
func(randNo);
break;
}
cout << "And now for something completely different." << endl;
for (size_t i = 0; i < 10; ++i) {
cout << i << ": ";
func(random());
}
}