Switch selection in runtime - c++

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;
}
}

Related

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.

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.

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 Case and For Loop 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 );
}