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 8 years ago.
Improve this question
So I tried running this piece of code and could not understand why it is giving me the output is giving me. If I input 4, why is the result 17?? I really don't get it. Can someone please explain?
#include<iostream>
using namespace std;
int main() {
int num;
int alpha = 10;
cout << "Enter a number :" << endl;
cin >> num;
switch(num) {
case 3:
alpha++;
break;
case 4:
case 6:
alpha = alpha + 3;
case 8:
alpha = alpha + 4;
break;
default:
alpha = alpha + 5;
}
cout << alpha << endl;
return 0;
}
If you don't have any break;in the body of acase(or something else that would exit the case, like agoto) execution will continue with the next case statement (it will fall through as it's usually known).
In your case entering 4 will do first the case 4:, then fall through tocase 6:and then tocase 8:and the end result will be alpha (10) + 3 + 4 = 17. since the case 8:has abreak;the switch statement will exit here.
On a side note, there's something called compound assignment +=that you can use to save some space, so instead of
alpha = alpha + 3;
you can do this:
alpha += 3;
A case statement works in the following way: The execution jumps to the matching case statement and continues until a break or the end of the switch block. Therefore, the statement after the case 8 is executed, too. So, 10+3+4=17.
Not writing a break at the end of a case block is considered as an error in most cases. In some cases it might be useful to continue with the execution, but this has to be commented very clearly to prevent confusions.
Related
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
I have been trying to make a C++ "math tutor" program. It's purpose is to ask the user if they want to do addition, subtraction, or multiplication, and once they make their selection and the calculation is complete, they are prompted to type in 0 to terminate the program and 1 to repeat it.
I tried using a do-while loop for this, but when I ran it, I found that as long as the user pressed 0 or 1, the program would repeat and it would never terminate.
Here's the code (without the math part as that really isn't relevant):
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
/*
* program to serve as math tutor for a young student
*/
int main(int argc, char** argv) {
int repeatChoice = 0;
//actual program has more variables here, but those are all math variables.
do {
//in this area was just code for the actual math part
cout << "Do you want to repeat this program (0 for no, 1 for yes)?" << endl;
cin >> repeatChoice;
while (repeatChoice != 0 && repeatChoice != 1) {
cout << "Invalid input. Please select 0 or 1." << endl;
cin >> repeatChoice;
}
if (repeatChoice = 0)
break;
} while (repeatChoice = 1);
return 0;
}
If anyone thinks seeing the full code will help, I'll edit the question to add it.
Please note that I'm new to programming and haven't researched any complex concepts really, so please if you can, explain it in relatively simple terms.
From what I can see the problem is in this part of the code:
...
if (repeatChoice = 0)
break;
} while (repeatChoice = 1);
...
You are using the assignment operator = instead of the comparison operator ==.
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 5 years ago.
Improve this question
Essentially my switch case is not working properly in that statements for conditions I don't think are met, are executing anyway.
Example input:
CerseiTyrion
Expected output:
Cersei
Tyrion
Actual output:
Cersei
Tyrion
Jon
Dany
Tyrion
Jon
Dany
The goal of the following function is to parse some input text for an adventure game, and let the game know about some of the important information contained within the text. It then continues to use what it finds to execute code that should always run with the rest of the function if certain conditions are met.
Minimal, complete; verifiable example:
void HandleGameState( const std::string& text ) {
enum Characters {
Cersei = 0x01,
Tyrion = 0x02,
Jon = 0x04,
Dany = 0x08
};
unsigned int mask = 1;
switch( characterMask & mask )
{
case Cersei:
{
std::cout << "Cersei" << std::endl;
};
case Tyrion:
{
std::cout << "Tyrion" << std::endl;
};
case Jon:
{
std::cout << "Jon" << std::endl;
};
case Dany:
{
std::cout << "Dany" << std::endl;
};
}
}
You need to finish your switch cases with break statements, otherwise code continues to the next case label.
Counter-intuitive to some people, switch is not glorified multi-if statement, but rather a glorified goto statement. Every case label behaves like goto label, and absent of break, the code will simply continue executing.
This is often used in cases when two different case labels need to produce the same output - instead of duplicating the code, the labels are simply put one after another. For example:
switch (x) {
case 1: // fall through
case 2: work_one_or_two(); break;
...
}
You have to use break behind every case.
The switch/case rule is easy, after a mached case, all following cases will be executed until a break; or end of switch.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
All,
So I've been really racking my brain about this one. I have a section of my program that needs to count spaces/vowels/characters in a user-specified string. This is one of those "teach you the way no one would do it because you can only used what we've covered in class already" kinds of assignments. So I have the user input a text, ending with a sentinel char, which in this case is '#'. The loop works wonderfully in regards to exiting when the sentinel is encountered, but it keeps iterating twice over string[0]. Here's the code:
i = 0;
characterToBeProcessed = userInputText.at(i);
while (characterToBeProcessed != LOOP_SENTINEL)
{
fout << characterToBeProcessed;
// Convert to lowercase
characterToBeProcessed =
static_cast<char> (tolower(characterToBeProcessed));
// Increment character counters
switch (characterToBeProcessed)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
totalVowelCount++;
totalCharacterCount++;
break;
case ' ':
totalSpaceCount++;
totalCharacterCount++;
break;
default:
totalCharacterCount++;
break;
}
characterToBeProcessed = userInputText.at(i++);
}
So when I input at the prompt:
"Please input a text to be analyzed, ending with the # character: "
Hi there, my friend!#
The output is:
Below is the text entered by the user:
HHi there, my friend!
Total characters: 21
Total vowels: 5
Total blank spaces: 3
I've had the program output the chars for .at(0) and .at(1), and those give me the correct characters, I just can't figure out why the loop iterates twice for the first char and then works fine after that second time through. The counts/output are otherwise correct except for the first char being duplicated. Any appreciation would be greatly appreciated.
As others have said, the right way to solve problems of this kind is to use a debugger. It would save you lots and lots of time.
But in any case, your error is that at the end of your while loop, you do this:
characterToBeProcessed = userInputText.at(i++);
But before your while loop, you do this:
characterToBeProcessed = userInputText.at(i);
Your problem is that you are not incrementing i each time you use it, which naturally results in the observed behavior.
A character at the first position is read twice
i = 0;
characterToBeProcessed = userInputText.at(i);
^^^^^^
while (characterToBeProcessed != LOOP_SENTINEL)
{
//...
characterToBeProcessed = userInputText.at(i++);
^^^^^^^^
}
If you need to use the while loop then it can look like
i = 0;
while ( ( characterToBeProcessed = userInputText.at( i++) ) != LOOP_SENTINEL )
{
//...
// remove the next statement
// characterToBeProcessed = userInputText.at(i++);
}
Also this statement
totalCharacterCount++;
is used under each label. It is better to place it outside the switch statement either before it or after it. For example
totalCharacterCount++;
switch (characterToBeProcessed)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
totalVowelCount++;
break;
case ' ':
totalSpaceCount++;
break;
default:
break;
}
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 7 years ago.
Improve this question
I'm just getting started with C++ and I've run into an error. It tells me that I have an "else" without a previous "If", but I do. I checked the case of the code and it looks basically just like the example from the website I'm learning from, it just has different sentences after all the couts, so I don't know what's wrong. Any help will be much appreciated.
int main()
{
int iOud;
cout<<"Type in your age: ";
cin >> iOud; //"a variable for the person's age
cin.ignore();
if (iOud < 20 );{
cout<< "A message\n";
}
else if (iOud > 40 ) {
cout << "A message\n";
}
else {
cout << "A message\n";
}
cin.get();
}
Drop the ; from if (iOud < 20 );{
if (iOud < 20 ); is a valid statement, so the compiler does not emit an error until it finds the invalid } else if. That's why the compiler error appears odd on first inspection.
The ; after if (iOud < 20) terminates the if statement.
Drop it, and you'd be fine
You ended the if(...) sentence with ; so it doesn't recognize it at all it, just sees the else if and drops the error. Drop the ; at if (iOud < 20 ); {.
And may I recommend using Switch/Case, if you are using multiple if sentences, but as Sean mentioned in the comment, this wouldn't apply for your example of comparing range of values.
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 8 years ago.
Improve this question
Hi I'm playing around with basic looping techniques and I'm trying to make the following code work. When the user inputs a number other than those allowed it will go to the default where I want to give them the option to try again (without just subbing the whole code into the default) or to just exit.
#include <iostream>
using namespace std;
int main(){
int input;
char ans;
cout<<"Hi please pick 1, 2 or 3: ";
cin>> input;
switch(input){
case 1:
cout<<"\nYou picked one\n";
break;
case 2:
cout<<"\nYou picked two\n";
break;
case 3:
cout<<"\nYou picked three\n";
break;
default:
cout<<"\nYou didn't pick a valid option.\nWould you like to try again?(y/n)";
cin>>ans;
if(ans== 'y'){
break;
}else{
continue;
}
}
}
When I run this I get the error that continue isn't in any loop. I'm not really quite sure how to use the continue statement. Any help with this would be greatly appreciated.
Put your switch statement inside a loop (while(1)) or (for(;;)), then it will work.
From http://en.cppreference.com/w/cpp/language/continue:
continue statement:
Causes the remaining portion of the enclosing for, range-for, while or do-while loop body skipped.
Used when it is otherwise awkward to ignore the remaining portion of the loop using conditional statements.
You need to put the core of your function in a for loop or while loop.
bool stop = false;
while ( !stop )
{
cout<<"Hi please pick 1, 2 or 3: ";
cin>> input;
stop = true;
switch(input){
case 1:
cout<<"\nYou picked one\n";
break;
case 2:
cout<<"\nYou picked two\n";
break;
case 3:
cout<<"\nYou picked three\n";
break;
default:
cout<<"\nYou didn't pick a valid option.\nWould you like to try again?(y/n)";
cin>>ans;
if(ans== 'y'){
stop = false;
}
}
}