#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++)
Related
I am trying to make a tic tac toe game in c++, but I am getting the following errors in my code(Not completed yet). am I passing the arrays to the function correctly
[Error] invalid conversion from 'char(*)[3]'to 'char'
and
[Error] initializing argument 1 of 'void player_input(char)'
#include <iostream>
using namespace std;
void draw_grid(char display[][3]){
cout<<"Board\n"<<"-------------"<<endl;
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
cout<<"| "<<display[x][y]<<" ";
}
cout<<"|"<<endl<<"-------------";
cout<<endl;
}
}
void player_input(char);
int main(){
char arr[3][3]={
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
draw_grid(arr);
player_input(arr);
draw_grid(arr);
return 0;
}
void player_input(char size[][3]){
char sign;
char number;
cout<<"X or O"<<endl;
cin>>sign;
cout<<"Choose a number\n";
cin>>number;
switch (number){
case '1':
size[0][0]=sign;
break;
case '2':
size[0][1]=sign;
break;
case '3':
size[0][3]=sign;
break;
case '4':
size[1][0]=sign;
break;
case '5':
size[1][1]=sign;
break;
case '6':
size[1][2]=sign;
break;
case '7':
size[2][0]=sign;
break;
case '8':
size[2][1]=sign;
break;
case '9':
size[2][2]=sign;
break;
}
}
void player_input(char);
Your function definition doesn't match the one below void player_input(char size[][3]). Before execution, the compiler tries to match each function call with its appropriate definition. It fails as it only sees the one above (which takes a single character), being matched with player_input(arr); with arr being a 2D array char arr[3][3].
You can modify the line above to make it work:
void player_input(char[3][3]);
Since you're using C++, you should ditch static arrays and consider using one of the modern C++ containers like std::vector.
Here's the fix:
#include <iostream>
using namespace std;
void draw_grid(char display[][3]){
cout<<"Board\n"<<"-------------"<<endl;
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
cout<<"| "<<display[x][y]<<" ";
}
cout<<"|"<<endl<<"-------------";
cout<<endl;
}
}
void player_input(char size[][3]){
char sign;
char number;
cout<<"X or O"<<endl;
cin>>sign;
cout<<"Choose a number\n";
cin>>number;
switch (number){
case '1':
size[0][0]=sign;
break;
case '2':
size[0][1]=sign;
break;
case '3':
size[0][3]=sign;
break;
case '4':
size[1][0]=sign;
break;
case '5':
size[1][1]=sign;
break;
case '6':
size[1][2]=sign;
break;
case '7':
size[2][0]=sign;
break;
case '8':
size[2][1]=sign;
break;
case '9':
size[2][2]=sign;
break;
}
}
int main(){
char arr[3][3]={
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
draw_grid(arr);
player_input(arr);
draw_grid(arr);
return 0;
}
You had 2 declarations of function player_input(). Also if you are not declaring the function type inside main(), you need to place the function definition before main().
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;
}
I have made a program in c++ for encoding and decoding morse code.
My program is working and the decoded message is fine but without spaces is there any way to add space.
#include <iostream>
#include <string>
using namespace std;
string translateMorseCode(string sentence);
string decoceMorseCode (string sentence);
int main()
{
string sentence;
cout<<"Enter word or sentence: ";
getline(cin,sentence);
cout<<"\nMorse Code is:\n";
//convert input message into morse
cout<<translateMorseCode(sentence)<<endl;
//copying morse code into decode string for decoding
string decode = translateMorseCode(sentence);
cout<<"\nDecoding morse code is text"<<endl;
//converting back ito text string
cout<<decoceMorseCode (decode);
return 0;
}
string decoceMorseCode (string sentence)
{
string delimiter = " ";
string decode ="";
int pos = 0;
string token;
while ((pos = sentence.find(delimiter)) != string::npos) {
token = sentence.substr(0, pos);
if(token==".-")
{
decode.append("a");
}
else if(token=="-...")
{
decode.append("b");
}
else if(token=="-.-.")
{
decode.append("c");
}
else if(token=="-..")
{
decode.append("d");
}
else if(token==".")
{
decode.append("e");
}
else if(token=="..-.")
{
decode.append("f");
}
else if(token=="--.")
{
decode.append("g");
}
else if(token=="....")
{
decode.append("h");
}
else if(token=="..")
{
decode.append("i");
}
else if(token==".---")
{
decode.append("j");
}
else if(token=="-.-")
{
decode.append("k");
}
else if(token==".-..")
{
decode.append("l");
}
else if(token=="--")
{
decode.append("m");
}
else if(token=="-.")
{
decode.append("n");
}
else if(token=="---")
{
decode.append("o");
}
else if(token==".--.")
{
decode.append("p");
}
else if(token=="--.-")
{
decode.append("q");
}
else if(token==".-.")
{
decode.append("r");
}
else if(token=="...")
{
decode.append("s");
}
else if(token=="-")
{
decode.append("t");
}
else if(token=="..-")
{
decode.append("u");
}
else if(token=="...-")
{
decode.append("v");
}
else if(token==".--")
{
decode.append("w");
}
else if(token=="-..-")
{
decode.append("x");
}
else if(token=="-.--")
{
decode.append("y");
}
else if(token=="--..")
{
decode.append("z");
}
else if(token=="-----")
{
decode.append("0");
}
else if(token==".----")
{
decode.append("1");
}
else if(token=="..---")
{
decode.append("2");
}
else if(token=="...--")
{
decode.append("3");
}
else if(token=="....-")
{
decode.append("4");
}
else if(token==".....")
{
decode.append("5");
}
else if(token=="-....")
{
decode.append("6");
}
else if(token=="--...")
{
decode.append("7");
}
else if(token=="---..")
{
decode.append("8");
}
else if(token=="----.")
{
decode.append("9");
}
sentence.erase(0,pos + delimiter.length());
}
return decode ; // returnung decoded text
}
//function convert input message into morse return Morse Code as String
string translateMorseCode(string sentence)
{
string MorseCode="";
for(int i=0;i<sentence.length();i++){
switch (sentence[i]){
case 'a':
case 'A':
MorseCode.append(".- ");
break;
case 'b':
case 'B':
MorseCode.append("-... ");
break;
case 'c':
case 'C':
MorseCode.append("-.-. ");
break;
case 'd':
case 'D':
MorseCode.append("-.. ");
break;
case 'e':
case 'E':
MorseCode.append(". ");
break;
case 'f':
case 'F':
MorseCode.append("..-. ");
break;
case 'g':
case 'G':
MorseCode.append("--. ");
break;
case 'h':
case 'H':
MorseCode.append(".... ");
break;
case 'i':
case 'I':
MorseCode.append(".. ");
break;
case 'j':
case 'J':
MorseCode.append(".--- ");
break;
case 'k':
case 'K':
MorseCode.append("-.- ");
break;
case 'l':
case 'L':
MorseCode.append(".-.. ");
break;
case 'm':
case 'M':
MorseCode.append("-- ");
break;
case 'n':
case 'N':
MorseCode.append("-. ");
break;
case 'o':
case 'O':
MorseCode.append("--- ");
break;
case 'p':
case 'P':
MorseCode.append(".--. ");
break;
case 'q':
case 'Q':
MorseCode.append("--.- ");
break;
case 'r':
case 'R':
MorseCode.append(".-. ");
break;
case 's':
case 'S':
MorseCode.append("... ");
break;
case 't':
case 'T':
MorseCode.append("- ");
break;
case 'u':
case 'U':
MorseCode.append("..- ");
break;
case 'v':
case 'V':
MorseCode.append("...- ");
break;
case 'w':
case 'W':
MorseCode.append(".-- ");
break;
case 'x':
case 'X':
MorseCode.append(".-- ");
break;
case 'y':
case 'Y':
MorseCode.append("-.-- ");
break;
case 'z':
case 'Z':
MorseCode.append("--.. ");
break;
case ' ':
MorseCode.append(" ");
break;
case '1':
MorseCode.append(".---- ");
break;
case '2':
MorseCode.append("..--- ");
break;
case '3':
MorseCode.append("...-- ");
break;
case '4':
MorseCode.append("....- ");
break;
case '5':
MorseCode.append("..... ");
break;
case '6':
MorseCode.append("-.... ");
break;
case '7':
MorseCode.append("--... ");
break;
case '8':
MorseCode.append("---.. ");
break;
case '9':
MorseCode.append("----. ");
break;
case '0':
MorseCode.append("----- ");
break;
}
}
return MorseCode;// return Morse Code
}
The problem is that you use a double space in your morse output to encode a word boundary, but your decoder skips all spaces. It therefore skips double spaces too, which is why it doesn't know where to put a space in the decoded output.
According to wiki:
Each character (letter or numeral) is represented by a unique sequence of dots
and dashes. The duration of a dash is three times the duration of a dot. Each
dot or dash is followed by a short silence, equal to the dot duration. The
letters of a word are separated by a space equal to three dots (one dash), and
the words are separated by a space equal to seven dots. The dot duration is the
basic unit of time measurement in code transmission.[1] To increase the speed of
the communication, the characters are encoded so the length of each character in
Morse is approximately inversely proportional to its frequency of occurrence in
English. Thus, the most common letter in English, the letter "E," has the
shortest code, a single dot.
So in my opinion:
Two "\s" should be between words.
One "\s" between single char.
#Neska gave you the basic answer but did not explain where the space gets interpreted.
When you get the tag decoded your logic should be able to detect the silence between the dots and dashes. Otherwise, it would not be able to determine where an individual character ends and the next character begins. That logic should detect the longer (seven dots long) interval between the end of a word and the beginning of the next work. Put in a special character (not a . or a dash) to be interpreted as a space in your morse code interpreter.
If you are interpreting text input and searching for the next delimiter (such as a space) in order to translate the dots and dashes, output the delimiters as well. That will put in the appropriate number of spaces
For example
.-^-^^-...^-.--
translates to
at^by
where the ^ character shows where the space should be.
Your code translates this as atby
I have found a solution by myself and it was quite simple - I just added
else if (" ")
{
decode.append(" ");
}
before the
sentence.erase(0,pos + delimiter.length());
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;
}
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 );
}