can we write this in C++ switch? - c++

#include <iostream>
using namespace std;
int main(){
char i;
cin >>i;
switch (i){
case ('e'||'i'||'o'||'u'||'a'):
cout<<"Vowel";
break;
case ('+'||'-'||'/'||'*'||'%'):
cout<<"Op";
break;
}
return 0;
}
if not than how can we use comparison or logical operators in switch ?
& why cant we declare and initialize variable in single case without using scope ?

Without a break statement the previous cases "fall through" so this achieves the || you were looking for:
#include <iostream>
using namespace std;
int main(){
char i;
cin >>i;
switch (i){
case 'e':
case 'i':
case 'o':
case 'u':
case 'a':
cout<<"Vowel";
break;
case '+':
case '-':
case '/':
case '*':
case '%':
cout<<"Op";
break;
}
return 0;
}
The answer to the other part of your question is discussed in depth already on stackoverflow.

You can use fallthrough to map multiple case values to the same action.
The diagnostic message explains it -- it would be possible to jump over the initialization. But isn't it just a warning?

No, you can't; in switches you can only implicitly use the == operator and only on integral and enumeration types (ยง6.4.2). You should rewrite that switch as
switch (i){
case 'e':
case 'i':
case 'o':
case 'u':
case 'a':
cout<<"Vowel";
break;
case '+':
case '-':
case '/':
case '*':
case '%':
cout<<"Op";
break;
}
which exploits the fall-through feature of the switch statement.
if not than how can we use comparison or logical operators in switch ?
Simply, you can't. If you want to do anything different than equality comparison with integral/enumeration types you have to write several if/else statements.
& why cant we declare and initialize variable in single case without using scope ?
It's not a problem of declaration, but of initialization; see the link in #awoodland's answer.

Format it like this:
switch (i)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
cout << "Vowel";
break;
}

Alternative, more terse solution:
#include <cstring>
// ...
if (strchr("eioua", i)) cout << "vowel";
if (strchr("+-/*%", i)) cout << "operator";
Note that strchr considers the terminating zero part of the string, so i should not be 0.

We could, except it doesn't mean what is intended (and yields the same value in both cases): you'd be performing a logical or on a bunch of non-zero integer values and the result is true in both cases.

Related

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

Empty Character Constant

Is there a way to bypass error C2137 on Visual Studio Community 2015? I am removing characters with stringstream but I do not want to replace them (even with a blank space), I want to erase them so, if I want to remove all 'o' in 'cool' it becomes 'cl' and not 'c l'. I saw in Stroustrup's book he wrote a if (...) ch = ''; but my compiler returns me an error and my best proxy is white space that's still unacceptable.
Here's my function with C2137:
string rem_vow(string& s)
{
for (char& c : s)
{
switch (c)
{
case 'A': case 'a': case 'E': case 'e': case 'I':
case 'i': case 'O': case 'o': case 'U': case 'u':
c = '';
break;
default:
break;
}
}
return s;
}
EDIT:
That's the code I saw in the book:
Thank you in advance
No, in order to remove a character in a string you will have to move the rest of the string one step, you cannot simple replace it with "empty" character. You could use the erase method though, but then you should probably not do that while iterating the string.
What you probably should do is to build a new string as you traverse the original string, something like:
string rem_vow(string const& s)
{
string res;
for (char c : s)
{
switch (c)
{
case 'A': case 'a': case 'E': case 'e': case 'I':
case 'i': case 'O': case 'o': case 'U': case 'u':
//c = ' ';
break;
default:
res.push_back(c);
break;
}
}
return res;
}

Using escape sequence at runtime with C++

I am quiet new with C++ and I need to read an input from a MSVC++ text-field and write it to a file. I need to write \n as a new line to the file and not as \n.
After some researching I found that escape characters only work at compile-time. Is it possible for me to use it on run-time. I am only using C++ for this task.
I might write this a bit differently if I were doing it in C++ today (I wrote this in C around 20 years ago), but it might at least provide a little inspiration:
/*
** Public Domain by Jerry Coffin.
**
** Interprets a string in a manner similar to that the compiler
** does string literals in a program. All escape sequences are
** longer than their translated equivalant, so the string is
** translated in place and either remains the same length or
** becomes shorter.
*/
#include <string.h>
#include <stdio.h>
#include "snip_str.h"
char *translate(char *string)
{
char *here=string;
size_t len=strlen(string);
int num;
int numlen;
while (NULL!=(here=strchr(here,'\\')))
{
numlen=1;
switch (here[1])
{
case '\\':
break;
case 'r':
*here = '\r';
break;
case 'n':
*here = '\n';
break;
case 't':
*here = '\t';
break;
case 'v':
*here = '\v';
break;
case 'a':
*here = '\a';
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
numlen = sscanf(here,"%o",&num);
*here = (char)num;
break;
case 'x':
numlen = sscanf(here,"%x",&num);
*here = (char) num;
break;
}
num = here - string + numlen;
here++;
memmove(here,here+numlen,len-num );
}
return string;
}

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