int number;
cin>>number;
switch (number)
{
case 1:
cout<<"My Favourite Subject is";
break;
case 2:
cout<<"Fundamentals of Programming";
break;
case 3:
cout<<"Exit";
break;
default:
cout<<"Invalid Data";
}
You replace switch statement with if-else
if (number == 1)
{
}
else if (number == 2)
{
}
...
{
}
else
{
// default here
}
//Hey this is fun!
int number;
cin>>number;
// ultra const!
static const char const * const table[] =
{
"Invalid Data",
"My Favourite Subject is",
"Fundamentals of Programming",
"Exit"
};
cout<<table[number&3];
//Who needs if statements!!?
Check whether number is equal to the first value from switch, if equal then output text, otherwise(else) check next number.
if ( number == /*put here value to check*/ )
// print some text
else
// do something else
This is my favorite, even though it is not what you asked for:
string res =
number==1 ? "My Favourite Subject is" :
number==2 ? "Fundamentals of Programming" :
number==3 ? "Exit" :
number==4 ? "Invalid Data" :
"";
cout<<res;
The good side here is that you don't have to constrain yourself to integer comparison. Instead of number==1 you can use any kind of complexComparisonReturningBoolean(number).
Also just for fun:
Just use capital letters and semi-colon instead of colon. Ah, and don't forget to add an evil macro :)
#define SWITCH(s) for(int switch_=s, b=1;b;b=0) {
#define CASE(n) } if ( switch_ == n ) {
#define DEFAULT }
int number;
cin>>number;
SWITCH(number)
{
CASE(1);
cout << "My Favourite Subject is";
break;
CASE(2);
cout << "Fundamentals of Programming";
break;
CASE(3);
cout << "Exit";
break;
DEFAULT;
cout << "Invalid Data";
}
This kill the 'switch' and if 'for' loop are not allowed, it is also possible to use a BREAK macro, but it is even more evil.
Replace the case statement with an if statement:
if (number == 1) {
cout<<"My Favourite Subject is";
} else if (number == 2) {
cout<<"Fundamentals of Programming";
} else if (number == 3) {
cout<<"Exit";
} else {
cout<<"Invalid Data";
}
if (number == 1) {
cout << "blah1";
}
else if (number == 2) {
cout << "blah2";
}
else if (number == 3) {
cout << "blah3";
}
else {
cout << "default";
}
Try :
if (number < 1 || number > 3) {
//
} else if (number == 1) {
//
} else if (number/2 == 1) {
//
} else if ((number - 1)/ 2 == 1) {
//
}
This helps you get more math expertise than just checking for equality.
Related
I'm trying to do a simple game Guess Number and created a while condition to do that, but I want to insert a question to play again if the player type "Y" on the queue or close the window if the player type "N". My way is not working and I didn't find a solution for this problem.
int main()
{
int guess, number;
char again;
srand(time(0));
number = rand() % 1000 + 1;
while (guess != number)
{
std::cout << "Enter the number guess between 1 and 1000: ";
std::cin >> guess;
if (guess < number)
{
std::cout << "Is more than this" << std::endl;
}
else if (guess > number)
{
std::cout << "Is less than this" << std::endl;
}
else if (guess < 1)
{
std::cout << "The value to guess is between 1 and 1000" << std::endl;
}
else if (guess > 1000)
{
std::cout << "The value to guess is between 1 and 1000" << std::endl;
}
else
{
std::cout << "This is the number" << std::endl;
std::cout << "Do want play again? [Y/N ]" << std::endl;
std::cin >> again;
if (again == 'N' || again == 'n')
{
break;
}
else if (again == 'Y' || again == 'y')
{
continue;
}
}
}
When you correctly guess the number, your while condition becomes false and hence the loop exits (i.e. guess becomes equal to number, and hence the condition guess != number is false). Try changing to condition of the while loop.
char again = 'Y';
while (again == 'Y' || again == 'y') { ... }
Starting with some presumably yet unrecognised problem: You won't reach all of your if branches:
if (guess < number)
{ }
else if (guess > number)
{ }
// now if you really get to the following else, guess was neither
// smaller nor greater than number, i. e. is EQUAL!
else if (guess < 1)
{ /* won't ever be entered as number(!) is never < 1 (be aware: guess == number) */ }
else if (guess > 1000)
{ /* won't ever be entered as number is never > 1000 */ }
else
{ }
You can solve in two variants, by moving the unreachable checks either in front of the initial ones:
if (guess < 1)
{ }
else if (guess > 1000)
{ }
else if (guess < number)
{ }
else if (guess > number)
{ }
else
{ }
or into them:
if (guess < number)
{
if (guess < 1)
{ }
else
{ }
}
else if (guess > number)
{
if (guess > 1000)
{ }
else
{ }
}
else
{ }
Now to the actual problem, let's consider the else:
// be aware that guess == number now!
if (again == 'N' || again == 'n')
{
break; // fine so far...
}
else if (again == 'Y' || again == 'y')
{
continue;
// re-enters the loop - be aware that the condition is still checked!!!
}
// and if none of all was entered???
// as is, we'd just go on with the loop body - as this was the last statement,
// though, the loop will be re-entered by checking the condition; i. e. if
// getting here, we do effectively exactly the same as in the second if check
// above...
OK, so you (implicitly) defined a default of 'y'. You then could just simply remove the second if (else if == y) and nothing would change.
However, the loop condition is not true any more (guess == number still applies!). Easiest now: just make an endless loop of:
for(;;)
{
if(again == 'n')
break;
// obsolete, just drop it:
//if(again == 'y')
// continue;
}
I personally, though, would rather have the 'n' as default (so typing 'x', 'q', 'a' all result in exiting as well), so I'd rather have:
for(;;)
{
if(again != 'y' && again != 'Y')
break;
}
I'm working with a partner, and we are both confused. VS tells us that "Function does not take 0 arguments" But we are both confused as to what that means. We are simply calling the arguments in an "if statement"
Would appreciate help on what I am misunderstanding. I am very new to functions and just trying to grasp what I am doing incorrectly.
int gradeSelection();
int choiceGrade;
char menu;
switch (choiceGrade)
{
case 1:
cout << "You have selected First Grade";
menuDisplay();
if (menu == '+')
{ // addition first grade
doAdditionFirstGrade();
}
else if (menu == '-') { // subtraction first grade
doSubtractionFirstGrade();
}
else if (menu == '*') { // multiplication first grade
doMultiplicationFirstGrade();
}
else if (menu == '/') { // division first grade
doDivisionFirstGrade();
}
else if (menu == '#') { // mixture first grade
doMixtureFirstGrade();
}
else if (menu == '0') { //exit program
cout << "Thank you for using the Math Tutor!" << endl;
}
else {
cout << "You have entered an invalid input, please try again" << endl;
}
break;
case 2: cout << "You have selected Second Grade";
menuDisplay();
if (menu == '+')
{ // addition second grade
doAdditionSecondGrade();
}
else if (menu == '-') { // subtraction second grade
doSubtractionSecondGrade();
}
else if (menu == '*') { // multiplication second grade
doMultiplicationSecondGrade();
}
else if (menu == '/') { // division second grade
doDivisionSecondGrade();
}
else if (menu == '#') { // mixture second grade
doMixtureSecondGrade();
}
else if (menu == '0') { //exit program
cout << "Thank you for using the Math Tutor!" << endl;
}
else {
cout << "You have entered an invalid input, please try again" << endl;
}
break;
case 3: cout << "You hace selected Third Grade";
menuDisplay();
if (menu == '+')
{ // addition third grade
doAdditionThirdGrade();
}
else if (menu == '-') { // subtraction third grade
doSubtractionThirdGrade();
}
else if (menu == '*') { // multiplication third grade
doMultiplicationThirdGrade();
}
else if (menu == '/') { // division third grade
doDivisionThirdGrade();
}
else if (menu == '#') { // mixture third grade
doMixtureThirdGrade();
}
else if (menu == '0') { //exit program
cout << "Thank you for using the Math Tutor!" << endl;
}
else {
cout << "You have entered an invalid input, please try again" << endl;
}
break;
case 0: cout << "Goodbye!";
default: cout << "Sorry, that was an invalid input.";
}
return 0;
}
in the "doAdditionFirstGrade" and the ones similar, is where I am getting the error.
They are called at the very beginning as:
void welcomeMessage();
int gradeSelection();
void menuDisplay();
int doAdditionFirstGrade(int num);
etc. (not going to link every bit of code to avoid confusion).
Then the actual function itself is:
int doAdditionFirstGrade(int num) {
}
return correct;
I didn't add all the code in the middle, because that part is not relevant to what I am trying to figure out.
The terminology is to call a function, not to open it. When you do this you must pass the correct arguments to the function.
The error message is telling you that you are attempting to call a function passing no arguments, while the function requires arguments. General ways to resolve this are:
remove the function calls,
provide the correct arguments for the calls, or
change the functions so that they do not require arguments.
I'd say that the 2nd one is the most common resolution, while the first one I listed is actually the least likely to be the correct approach. Which one is correct depends on the situation.
I can't really tell from the code you posted how the pieces of your program should fit together. You are not using the return value of doAdditionFirstGrade() and don't appear to have a value for, or be using its parameter, so my guess is that you want something more like:
// stuff ...
void welcomeMessage();
int gradeSelection();
char menuDisplay();
void doAdditionFirstGrade();
// other declarations
int someFunction()
{
int gradeSelection();
int choiceGrade;
char menu;
// get choice grade somehow
switch (choiceGrade)
{
case 1:
cout << "You have selected First Grade";
menu = menuDisplay();
if (menu == '+')
{ // addition first grade
doAdditionFirstGrade();
}
else if (menu == '-') { // subtraction first grade
doSubtractionFirstGrade();
}
else if (menu == '*') { // multiplication first grade
doMultiplicationFirstGrade();
}
else if (menu == '/') { // division first grade
doDivisionFirstGrade();
}
else if (menu == '#') { // mixture first grade
doMixtureFirstGrade();
}
else if (menu == '0') { //exit program
cout << "Thank you for using the Math Tutor!" << endl;
}
else {
cout << "You have entered an invalid input, please try again" << endl;
}
break;
// other cases
default:
cout << "Sorry, that was an invalid input.";
break;
}
return 0;
}
void doAdditionFirstGrade()
{
// do stuff
return;
}
If doAdditionFirstGrade() really does require a parameter, then this is wrong and you must get the proper value somehow and pass it in the function call.
Note that I have also changed the usage of the menuDisplay() function to return the value of the choice rather than (apparently) use a global variable to communicate the result. I'd consider this an improvement, but it is not what you are asking about and it would require you to make a corresponding change to the menuDisplay() function itself.
how do I run only one of those if statements in a for loop? For example i have an input of 5...and i just want it to print five...but whenever i run this code, it will execute all if statement..please help me
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// Complete the code.
int a;
int b;
cin >> a;
for (a = 0; 0<a<10; a++)
{
if (a == 1)
{
cout << "one";
}
if (a == 2)
{
cout << "two";
}
if (a == 3)
{
cout << "three";
}
if (a == 4)
{
cout << "four";
}
if (a == 5)
{
cout << "five";
}
if (a == 6)
{
cout << "six";
}
if (a == 7)
{
cout << "seven";
}
if (a == 8)
{
cout << "eight";
}
if (a == 9)
{
cout << "nine";
}
else if (a > 9 && a%2 == 0)
{
cout << "even";
}
else if (a > 9 && a&2 != 0)
{
cout << "odd";
}
}
return 0;
}
The problem seems to be the for loop. Your program accepts a value for a as an input, but then as soon as the loop begins, it resets the value of a to 0 (for (a = 0;...
Therefore it's looping 10 times, and on each loop a will have a different value, starting from 0 and ending at 9. This means that all of your if statements will get hit at some point in the execution, generally one on each of the loops round the for.
To get your expected behaviour " input of 5...and i just want it to print five", simply remove the for loop from your code.
Your unnecessary for loop trashes the input value of a and loops forever! (At least until you overflow your signed type a).
You are replacing a by using it as the counter in the for loop! If you only ever want one output, then drop the for loop completely. If your for loop were to remain then your expression 0 < a < 10 ought to be recast as 0 < a && a < 10 : formally 0 < a < 10 is evaluated as (0 < a) < 10 which is either true < 10 or false < 10 which is always true.
Also consider refactoring your if else to set up explicitly mutually exclusive statements:
if (a == 1){
cout << "one";
} else if (a == 2){
cout << "two";
/*and so on*/
} else {
/*all other cases*/
}
Although in this case you might want to consider a switch block:
switch (a){
case 1:
cout << "one";
break; // to stop program control flowing into the next case
case 2:
cout << "two";
break;
/*and so on*/
default:
/*all other cases*/
}
if () {
} else if () {
}
Although,
switch() {
}
will be more efficient in your case.
Update 1
#Aleph0
Below is the solution
int main() {
int a;
cin >> a;
switch (a) {
case 1: cout << "one"; break;
case 2: cout << "two"; break;
case 3: cout << "three"; break;
case 4: cout << "four"; break;
case 5: cout << "five"; break;
case 6: cout << "six"; break;
case 7: cout << "seven"; break;
case 8: cout << "eight"; break;
case 9: cout << "nine"; break;
default: cout << ((a & (1 << 31)) ? "negative" : (a & 1) ? "odd" : "even"); break;
}
}
Question has been asked to do following
i have an input of 5...and i just want it to print five
And, someone has correctly mentioned above, for loop is immaterial here.
To start, I'm trying to make a GPA calculator for my class.
I know how to compare strings, so I'm good there. The issue I'm having is that I'm trying to set up a situation so when the user inputs anything other than a letter grade value, it will return an error message. I've set up two arrays, one that stores string values and another that stores integral values. The idea was to use the string array to store the entered grade letter inputs, then use those to determine the GPA value for each class. It would then store that value into the integral array. I hate to be obnoxious, but here's the code for the first section alone:
void gpaCalSetClassNum5(){
string mathWeight5;
string scienceWeight5;
string historyWeight5;
string englishWeight5;
string elective1Weight5;
string elective2Weight5;
string gpaClassSet5[] = {"null", "null", "null", "null", "null"};
int gpaClassSet5int[] = {};
cout << "Enter the grade value of each of your classes." << endl;
/////////////////////////
MATH:
cout << "Math" << endl;
cin >> gpaClassSet5[0];
if (gpaClassSet5[0] == "A") {
gpaClassSet5int[0] = 4;
} else if (gpaClassSet5[0] == "a") {
gpaClassSet5int[0] = 4;
} else if (gpaClassSet5[0] == "B") {
gpaClassSet5int[0] = 3;
} else if (gpaClassSet5[0] == "b") {
gpaClassSet5int[0] = 3;
} else if (gpaClassSet5[0] == "C") {
gpaClassSet5int[0] = 2;
} else if (gpaClassSet5[0] == "c") {
gpaClassSet5int[0] = 2;
} else if (gpaClassSet5[0] == "D") {
gpaClassSet5int[0] = 1;
} else if (gpaClassSet5[0] == "d") {
gpaClassSet5int[0] = 1;
} else if (gpaClassSet5[0] == "F") {
gpaClassSet5int[0] = 0;
} else if (gpaClassSet5[0] == "f") {
gpaClassSet5int[0] = 0;
} else if (gpaClassSet5[0] != ){
cout << "Did you enter a letter grade value?" << endl;
goto MATH;
}
cout << "You have selected " << gpaClassSet5[0] << ", or " << gpaClassSet5int[0] << endl;
cout << "Is this class weighted? Use Y/N." << endl;
cin >> mathWeight5;
if (mathWeight5 == "Y" || "y") {
gpaClassSet5int[0] = gpaClassSet5int[0] + 1;
}
I'm looking for a simplified version of this. Why can't I use something like:
if(gpaClassSet5[0] == "A" || "a"){
//stuff//
}
I'm in need of a simplified version because, like a switch, I'd like to use different inputs to do different things -- but ultimately have a default in case any of the values listed weren't entered.
How can I do this? How can I set up a switch in C++?
Sorry if this question is a little dumb, I'm getting into C++ and these self-made programs are really my only practice.
Full program code here: http://justpaste.it/ee4u
Because that's not how C++ is specified to work, you need to do the comparison twice:
if(gpaClassSet5[0] == "A" || gpaClassSet5[0] == "a")
The logical OR operation means "if the left-hand expression is true, or the right-hand expression is true". In your case with the code as in your question, the right-hand side expression will always be true as "a" is not zero (i.e. false).
Operator precedence says you can't do it this way. gpaClassSet5[0] == "A" || "a" is the same as (gpaClassSet5[0] == "A") || ("a").
If you don't want to write gpaClassSet5[0] twice, you could use regular expressions if you don't mind a performance hit
std::regex_match(gpaClassSet5[0], std::regex("A|a"));
This gets more sensible if you test against a lot of possible matches:
std::regex_match(gpaClassSet5[0], std::regex("A|Grade A|1|Excellent|Outstanding|Perfect|Perfect Score)"));
If you are not using C++11 (don't have std::regex), you can use boost::regex from boost.org.
Or you could solve your specific code example with more compact logic:
char gradeLetter = std::tolower(gpaClassSet5[0])
if (gradeLetter >= 'a' && gradeLetter <= 'd')
gpaClassSet5int[0] = 4-(gradeLetter -'a');
else if (gradeLetter == 'f')
gpaClassSet5int[0] = 0;
else
{
cout << "Did you enter a letter grade value?" << endl;
goto MATH;
}
And extract a function to get rid of the goto and make the code easier to read:
int ConvertLetterToNumericGrade(char gradeLetter)
{
char lower = std::tolower(gradeLetter);
if (lower >= 'a' && lower <= 'd')
return 4-(lower -'a');
if (lower == 'f')
return 0;
throw std::runtime_error("cannot convert invalid grade letter");
}
void gpaCalSetClassNum5()
{
...
while (true)
{
cin >> gpaClassSet5[0];
try { gpaClassSet5int[0] = ConvertLetterToNumericGrade(gpaClassSet5[0]); }
catch (const std::runtime_error& )
{
cout << "Did you enter a letter grade value?" << endl;
continue;
}
break;
}
...
}
And with a switch (which is not supported for strings, but is supported for char and wchar):
int ConvertLetterToNumericGrade(char gradeLetter)
{
switch (gradeLetter)
{
case 'a':
case 'A':
return 4;
case 'b':
case 'B':
return 3;
case 'c':
case 'C':
return 2;
case 'd':
case 'D':
return 1;
case 'f':
case 'F':
return 0;
default:
cout << "Did you enter a letter grade value?" << endl;
throw std::runtime_error("cannot convert invalid grade letter");
}
}
Resp.
int ConvertLetterToNumericGrade(char gradeLetter)
{
switch (std::tolower(gradeLetter))
{
case 'a': return 4;
case 'b': return 3;
case 'c': return 2;
case 'd': return 1;
case 'f': return 0;
default:
cout << "Did you enter a letter grade value?" << endl;
throw std::runtime_error("cannot convert invalid grade letter");
}
}
I was about to write a C++ function doing the following:
1 ---> "1st"
2 ---> "1nd"
3 ---> "3rd"
...
17657 --> "17657th"
...
i.e. produces the ordinal extension string for that number (it doesn't have to do an itoa() of the number itself). But then I thought "surely something in the standard library or boost does this already?"
Notes:
I know it's not hard to write this, there's an implementation in Python right here on SO, I just don't want to duplicate code.
I need this in English, obviously. A multi-language version would be nice for political-correctness considerations, not more than that...
Here's what I ended up writing:
const char* ordinal_suffix(int n)
{
static const char suffixes [][3] = {"th", "st", "nd", "rd"};
auto ord = n % 100;
if (ord / 10 == 1) { ord = 0; }
ord = ord % 10;
if (ord > 3) { ord = 0; }
return suffixes[ord];
}
The code golf solutions are cute, but - they really do optimize for terseness, not anything else. This is faster (although it could be made even faster by putting the suffixes in a .cpp out of the function body and making the code inlinable), much clearer, and still more terse than most other answers here.
// Returns numbers with ordinal suffix as string
// Based on https://stackoverflow.com/questions/3109978/display-numbers-with-ordinal-suffix-in-php
std::string NumberToOrdinal(size_t number) {
std::string suffix = "th";
if (number % 100 < 11 || number % 100 > 13) {
switch (number % 10) {
case 1:
suffix = "st";
break;
case 2:
suffix = "nd";
break;
case 3:
suffix = "rd";
break;
}
}
return std::to_string(number) + suffix;
}
I'm pretty sure you can adapt the four line solution at Display numbers with ordinal suffix in PHP. Unfortunately, I don't think there is such a thing in a common C++ lib.
try this...
#include <iostream>
using namespace std;
void suffix(int n, char suff[]);
// creates the ordinal suffix
// for a given number
int main()
{
char s[5];
int x;
cout << "Enter a number to find the ordinal suffix for ";
cin >> x;
suffix(52111,s);
}
void suffix(int n, char suff[])
{
if(n%100 == 11 || n%100 == 12 || n%100 == 13)
{
cout << "suffix is: " << n << "th";
cout << endl;
}
else
{
if(n%10 == 1)
{
cout << "Suffix is: " << n << "st";
cout << endl;
}
else
{
if(n%10 == 2)
{
cout << "Suffix is: " << n << "nd";
cout << endl;
}
else
{
if(n%10 == 3)
{
cout << "Suffix is: " << n << "rd";
cout << endl;
}
else
{
if(n%10 == 4 || n%10 == 5 || n%10 == 6 || n%10 == 7 || n%10 == 8 || n%10 == 9 || n%10 == 0)
{
cout << "Suffix is: " << n << "th";
cout << endl;
}
}
}
}
}
}
I used the following string function to accomplish it.
#include <string>
#include <iostream>
using namespace std;
string ordinal(int i)
{
if(i==1)
{
return "First";
}
if(i==2)
{
return "Second";
}
if(i==3)
{
return "Third";
}
if(i==4)
{
return "Fourth";
}
if(i==5)
{
return "Fifth";
}
if(i==6)
{
return "Sixth";
}
if(i==7)
{
return "Seventh";
}
if(i==8)
{
return "Eighth";
}
}
int main()
{
for(int i=0; i<8; i++)
{
cout << ordinal(i+1) << " number: ";
}
return 0;
}
#include <iostream>
#include <string>
std::string number_to_ordinal(int number)
{
// Convert number to string
std::string ordinal = std::to_string(number);
// Get the last character of the number to later determine ordinal indicator
char last_char = ordinal.back();
// Get the last two characters of the number to deal with ordinal indicator conditions
std::string last_two_char;
if(ordinal.size() > 1)
last_two_char = ordinal.substr(ordinal.size() - 2, ordinal.size());
// Determine ordinal indicator. Each number with a last character ending in '1', '2',
// and '3' require ordinal indicators of 'st', 'nd', and 'rd', respectively. However,
// numbers with the last two characters ending in '11', '12', and '13' require 'th'
// as the ordinal indicator.
if(last_two_char != "11" && last_char == '1')
ordinal += "st";
else if (last_two_char != "12" && last_char == '2')
ordinal += "nd";
else if (last_two_char != "13" && last_char == '3')
ordinal +="rd";
else
ordinal += "th"; // All other numbers require 'th' as the ordinal indicator
return ordinal;
}
///////////////////////////////////////////////////////////////////////
// Main Program
///////////////////////////////////////////////////////////////////////
int main()
{
// Test number to ordinal
for(int i = 17657; i < 17725; i++)
std::cout << number_to_ordinal(i) << std::endl;
return 0;
}