Switch Case and For Loop C++ - c++

Hello I have this code and I cant seem to get it to work. The loop loops for three times and then the addCourse is suppose to add all three selections. The problem is the addCourse function only adds the last bit for all three selections. Example :
If I select 1 2 3 then it is suppose to give out:
Maths
Quantum
Reality
Instead it gives out:
Reality
Reality
Reality
(All three is the case 3 which is selected last)
How do I sort this problem. Thank you. Below is the code.
for(int p = 0; p < 3; p++)
{
cout << "Please select a course:" <<endl;
cout<<"1. Maths\n";
cout<<"2. Quantum\n";
cout<<"3. Reality\n";
cin >> coursepick;
switch (coursepick)
{
case 1: course= "Maths";
case 2: course= "Quantum";
case 3: course= "Reality";
default: break;
}
cout << "Please insert the course mark:" <<endl;
cin >> mark;
cin.ignore();
phys[0]->addCourse(course,mark);
}

switch (coursepick)
{
case 1: course= "Maths"; break;
case 2: course= "Quantum"; break;
case 3: course= "Reality"; break;
default: break;
}
if you don't break at the end of each case, it just continue with the next, and the next, and then until case 3 and break on default.

In C++, case statements automatically move on to the next. You must insert break after each case.
switch (coursepick)
{
case 1: course= "Maths"; break;
case 2: course= "Quantum"; break;
case 3: course= "Reality"; break;
default: break;
}

In your switch statement you need a break statement in each case. Without a break statement C will fall to the next case. You case statement is equivalent to:
course= "Maths";
course= "Quantum";
course= "Reality";
Instead it needs to be:
switch (coursepick)
{
case 1: course= "Maths"; break;
case 2: course= "Quantum"; break;
case 3: course= "Reality"; break;
default: break;
}

As mentioned in the other posts, you need to end each case with the keyword "break;" if you don't want it to trickle down into the next case.
switch (coursepick)
{
case 1: course= "Maths"; break;
case 2: course= "Quantum"; break;
case 3: course= "Reality"; break;
default: break;
}
Switch statements have this behavior because sometimes you want it to filter through multiple cases. This saves you from having to duplicate code when multiple cases have the same result. The following example shows the equivalent of if case 'a' OR case 'A', do this. If case 'b' OR 'B', do this.
switch (input)
{
case 'a':
case 'A': text = "Letter A"; break;
case 'b':
case 'B': text = "Letter B"; break;
default: text = "Not A or B"; break;
}

Dude Can you add Break tag for all the case statements. It Should be like this
switch (coursepick)
{
case 1: course= "Maths";
break;
case 2: course= "Quantum";
break;
case 3: course= "Reality";
break;
default: break;
}
If you don't mention it will be through all the cases and finally in case three course will be over written by Reality.
So break is necessary for case statements

As it was already said you have to use break for any case label.
switch (coursepick)
{
case 1: course= "Maths"; break;
case 2: course= "Quantum"; break;
case 3: course= "Reality"; break;
default: break;
}
But in any case the code is invalid bacause if the user will enter a number outside the acceptable range variable course will not be assigned. However you will use this unassigned variable in statement
phys[0]->addCourse(course,mark);
Also it is not clear why the variable is defined outside the loop.
I would write the loop the following way
enum { Maths = 1, Quantum, Reality };
for ( int p = 0; p < 3; p++ )
{
do
{
cout << "\nPlease select a course:" <<endl;
cout<<"1. Maths\n";
cout<<"2. Quantum\n";
cout<<"3. Reality\n";
cin >> coursepick;
if ( !( Maths <= coursepick && coursepick <= Reality ) )
{
cout << "Error. Invalid input. Please repeat" << std::endl;
}
} while ( !( Maths <= coursepick && coursepick <= Reality ) );
switch (coursepick)
{
case Maths: course= "Maths"; break;
case Quantum: course= "Quantum"; break;
case Reality: course= "Reality"; break;
default: abort();
}
cout << "Please insert the course mark:" << endl;
cin >> mark;
cin.ignore();
phys[0]->addCourse( course, mark );
}

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.

I solved a thing, don't know the reason behind

I did a program that translates number into roman numbers, and I was about to show it to a friend of mine when the .exe file didn't work. It asked the user which number to put in, and after he put it the program closed. What I don't understand is why it did work after compiling on DevC++, but had a different behavior as a .exe
I found few solutions out there, and the one that worked for me was to add a:
int a;
cin>>a;
Before returning a cero. Now it works. I don't understand how the console doesn't execute the actions given without that. I'm leaving the code here.
#include <iostream>
using namespace std;
int main(){
int numero, unidades, decenas, centenas, millares;
int comprobante;
cout<<"Este programa traduce un numero de 4 cifras a numeros romanos.\nDigite un numero de
maximo cuatro cifras: ";
cin>>numero;
unidades= numero%10;
numero /= 10;
decenas= numero%10;
numero/=10;
centenas= numero%10;
numero/=10;
millares=numero;
comprobante=millares/10;
if(comprobante==0){
cout<<"Su numero traducido a numeros romanos es: ";
switch(millares){
case 1: cout<<"M"; break;
case 2: cout<<"MM"; break;
case 3: cout<<"MMM"; break;
}
switch(centenas){
case 1: cout<<"C"; break;
case 2: cout<<"CC"; break;
case 3: cout<<"CCC"; break;
case 4: cout<<"CD"; break;
case 5: cout<<"D"; break;
case 6: cout<<"DC"; break;
case 7: cout<<"DCC"; break;
case 8: cout<<"DCCC"; break;
case 9: cout<<"CM"; break;
}
switch(decenas){
case 1: cout<<"X"; break;
case 2: cout<<"XX"; break;
case 3: cout<<"XXX"; break;
case 4: cout<<"XL"; break;
case 5: cout<<"L"; break;
case 6: cout<<"LX"; break;
case 7: cout<<"LXX"; break;
case 8: cout<<"LXXX"; break;
case 9: cout<<"XC"; break;
}
switch(unidades){
case 1: cout<<"I"; break;
case 2: cout<<"II"; break;
case 3: cout<<"III"; break;
case 4: cout<<"IV"; break;
case 5: cout<<"V"; break;
case 6: cout<<"VI"; break;
case 7: cout<<"VII"; break;
case 8: cout<<"VIII"; break;
case 9: cout<<"IX"; break;
}
}
else{
cout<<"Te dije de 4 cifras. Por desgraciado me cierro.";
}
int a;
cin>>a;
return 0;
}
The program closes immediately in the terminal when the program reaches completion. When you cin>>a it is waiting for input before closing. See this.
Include
#include<conio.h>
And add getch(); at the end of your code. This will make your console to not close.
Your code was totally fine.
It is that when the main() reached return 0; that means it is done. And if you are running it as an .exe file, that means the program is done. And when a program is done, it would be closed.
There are couple ways to make it stay not closed. One that many have mentioned is to add a cin >> something; or getch(); with #include <conio.h> for windows at the end, so it would wait till you enter something.
Also you could delay the program before it reaches the return statement. You can check here How do you add a timed delay to a C++ program?
You could also wrap you entire program with a while loop, like:
while(true)
{
// Your programs here
if(someCondition) break;
};
where someCondition is a bool type, maybe char c; cin >> c; bool someCondition = (c == 'x'); So that the program only ends if someone input 'x', else it would run again.

Confusion Converting Hexadecimal to Binary in C++

#include <string>
#include <iostream>
using namespace std;
int main() {
string input, numBin = "";
cout << "Enter a hexadecimal number: ";
getline(cin, input);
for (int i = 0; i < input.length(); i++) {
switch (input[i]) {
case 0: numBin.append("0000"); break;
case 1: numBin.append("0001"); break;
case 2: numBin.append("0010"); break;
case 3: numBin.append("0011"); break;
case 4: numBin.append("0100"); break;
case 5: numBin.append("0101"); break;
case 6: numBin.append("0110"); break;
case 7: numBin.append("0111"); break;
case 8: numBin.append("1000"); break;
case 9: numBin.append("1001"); break;
case 'a': numBin.append("1010"); break;
case 'A': numBin.append("1010"); break;
case 'b': numBin.append("1011"); break;
case 'B': numBin.append("1011"); break;
case 'c': numBin.append("1100"); break;
case 'C': numBin.append("1100"); break;
case 'd': numBin.append("1101"); break;
case 'D': numBin.append("1101"); break;
case 'e': numBin.append("1110"); break;
case 'E': numBin.append("1110"); break;
case 'f': numBin.append("1111"); break;
case 'F': numBin.append("1111"); break;
default: break;
}
}
cout << "Your number in binary is " << numBin << ".";
}
This program is supposed to change a hexadecimal input ('input') into a binary result ('numBin'). I don't have much experience using switch statements and do not fully understand the "default" case, so any clarification about that or if I am using it incorrectly would be helpful!
The error I'm getting is on the for loop, and it thorws: comparison between signed and unsigned integer expressions [-Wsign-compare]
In the line:
for (int i = 0; i < input.length(); i++) ...
input.length() returns a size_t, which is a unsigned type.
(see http://www.cplusplus.com/reference/string/string/length/)
Comparing signed and unsigned values is not safe, which is why the compiler warns you, read more about it in this post among many others:
A warning - comparison between signed and unsigned integer expressions
To fix it, simply change to
unsigned int i = 0
The default switch case will be executed when none of the other cases match. You should put some code there that handles incorrect input for example.
case '0':
case '1':
...
Use all characters..not number and characters.
And one ore thing..for(i=0;i<(int) input.length();i++)

C++ Problems modifying string with numbers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
I have made a simple encryption function,which encrypts everything except 0-9 numbers (ignoring the special characters).
Here is the code.
#include <iostream>
using namespace std;
void encrypt(char s[])
{
char *ptr;
ptr=s;
while(*ptr)
{
switch (*ptr)
{
case 'a': *ptr='b';
break;
case 'b': *ptr='a';
break;
case 'c': *ptr='z';
break;
case 'd': *ptr='y';
break;
case 'e': *ptr='c';
break;
case 'f': *ptr='d';
break;
case 'g': *ptr='x';
break;
case 'h': *ptr='g';
break;
case 'i': *ptr='i';
break;
case 'j': *ptr='h';
break;
case 'k': *ptr='f';
break;
case 'l': *ptr='j';
break;
case 'm': *ptr='q';
break;
case 'n': *ptr='o';
break;
case 'o': *ptr='p';
break;
case 'p': *ptr='m';
break;
case 'q': *ptr='n';
break;
case 'r': *ptr='l';
break;
case 's': *ptr='k';
break;
case 't': *ptr='x';
break;
case 'u': *ptr='w';
break;
case 'v': *ptr='u';
break;
case 'w': *ptr='v';
break;
case 'x': *ptr='t';
break;
case 'y': *ptr='s';
break;
case 'z': *ptr='r';
break;
case 1: *ptr=5;
break;
case 2: *ptr=6;
break;
case 3: *ptr=0;
break;
case 4: *ptr=1;
break;
case 5: *ptr=2;
break;
case 6: *ptr=7;
break;
case 7: *ptr=4;
break;
case 8: *ptr=3;
break;
case 9: *ptr=8;
break;
case 0: *ptr=9;
break;
default: *ptr=*ptr;
break;
}
*ptr++;
}
*ptr='\0';
}
int main()
{
char password[10];
cout<<"Enter the password\n";
cin>>password;
encrypt(password);
cout<<password<<endl;
return 0;
}
Here is a sample output
sh-4.3$ main
Enter the password
thisisanex!!1234567
xgikikboct!!1234567
You need to use the character '1' not the integer value 1.
So use case '1': instead of case 1: and so on for the other numbers.
As nos said, the character is different from the integer value.
However, looking at your code, it would make a lot more sense to do this:
#include <iostream>
#include <string>
using namespace std;
int main(){
string charset = "abcdefghijklmnopqrstuvwxyz1234567890";
string scrambledcharset = "r5b6ng1fcl8htau9i74kxy0vjw3psemqz2do"; //Whatever order you want
string uIn;
string output;
cout << "Enter your string: ";
cin >> uIn;
cin.ignore();
for(int i = 0; i < uIn.length(); i++){
for(int j = 0; j < charset.length(); j++){
if(uIn[i] == charset[j]){
output += scrambledcharset[j];
}
}
}
cout << "\nScrambled: " << output;
return 0;
}

Switch selection in runtime

Situation: There are 5 channel and they are assigned to any of 5 sensors(it can be changed runtime). Ex- channel 1 and 2 can be assigned to sensor 1.
However, I want that irrespective of assignment, all the sensor case in second switch get executed only once for the complete "For" loop cycle.
I wrote following code but its not working. Can anyone tell the solution for this?
for(uChannel = 0; uChannel < 5; uChannel++) {
switch(uChannel)
{
case 0: sensor= calibrate.channel1;
break;
case 1: sensor= calibrate.channel2;
break;
case 2: sensor= calibrate.channel3;
break;
case 3: sensor= calibrate.channel4;
break;
case 4: sensor= calibrate.channel5;
break;
default:
}
switch(sensor)
{
case 1: function(a,b);
break;
case 2: function(c,b);
break;
case 3: function(d,b);
break;
case 4: function(e,b);
break;
case 5: function(f,b);
break;
default
}
}
You can write function for second switch case and call it from every case of first switch For ex:
void executeSensor(int sensor){
switch(sensor)
{
case 1: function(a,b);
break;
case 2: function(c,b);
break;
case 3: function(d,b);
break;
case 4: function(e,b);
break;
case 5: function(f,b);
break;
default:
break;
}
}
call in this way:
for(uChannel = 0; uChannel < 5; uChannel++) {
switch(uChannel)
{
case 0: sensor= calibrate.channel1;
executeSensor(sensor)
break;
case 1: sensor= calibrate.channel2;
executeSensor(sensor)
break;
case 2: sensor= calibrate.channel3;
executeSensor(sensor)
break;
case 3: sensor= calibrate.channel4;
executeSensor(sensor)
break;
case 4: sensor= calibrate.channel5;
executeSensor(sensor)
break;
default:
break;
}
}
In above code there are two compilation error.
First you should fix that. Default case should be ended with break statement and ;
for(uChannel = 0; uChannel < 5; uChannel++) {
switch(uChannel)
{
case 0: sensor= calibrate.channel1;
break;
case 1: sensor= calibrate.channel2;
break;
case 2: sensor= calibrate.channel3;
break;
case 3: sensor= calibrate.channel4;
break;
case 4: sensor= calibrate.channel5;
break;
default:
break;
}
switch(sensor)
{
case 1: function(a,b);
break;
case 2: function(c,b);
break;
case 3: function(d,b);
break;
case 4: function(e,b);
break;
case 5: function(f,b);
break;
default:
break;
}
}