Convert Hex To Binary Function Adding Extra Values - c++

The ConvertHexToBinary function returns the proper binary string....followed by a bunch extra 0 & 1s
Cant figure out why the extra is being tacked on.
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;
string ConvertHexToBinary(string str) {
string ToReturn;
for (int i = 2; i < str.size(); i++) {
switch (str[i]) {
case '0':
ToReturn.append("0000");
case '1':
ToReturn.append("0001");
case '2':
ToReturn.append("0010");
case '3':
ToReturn.append("0011");
case '4':
ToReturn.append("0100");
case '5':
ToReturn.append("0101");
case '6':
ToReturn.append("0110");
case '7':
ToReturn.append("0111");
case '8':
ToReturn.append("1000");
case '9':
ToReturn.append("1001");
case 'A':
ToReturn.append("1010");
case 'B':
ToReturn.append("1011");
case 'C':
ToReturn.append("1100");
case 'D':
ToReturn.append("1101");
case 'E':
ToReturn.append("1110");
case 'F':
ToReturn.append("1111");
}
}
return ToReturn;
}
int main()
{
int x = 25;
int *p = &x;
cout << p << endl;
std::ostringstream str;
str << p;
std::cout << str.str() << endl;
cout << ConvertHexToBinary(str.str()) << endl;
}

Related

Using while>>cin to keep asking user for input in C++

Code for a blackjack card counting program.
the issue is that it does not exit the while loop upon receiving no cin input from the user.
for example)
User would input x chars and then hit enter to exit the while loop.
#include<iostream>
using namespace std;
int main(){
int count = 0;
char currcard;
cout<<"Enter cards seen on table: "<<endl;
while (cin>>currcard)
{
switch (currcard)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
count++;
break;
case '7':
case '8':
case '9':
break;
case 'A':
case 'J':
case 'Q':
case 'K':
count--;
break;
default:
cout<<"Invalid Entry";
break;
}
}
cout <<"Current count: "<< count << endl;
//user enter cards seen on table and if below 7 increment
//based on count the program returns if you should hit or quit
return 0;
}
Expecting program to exit when enter is hit by user
You can use cin.get() like this.
while (cin>>currcard)
{
// your logic
if (cin.get() == '\n') {
break;
}
}
In this way, your input is supposed to be something like 1 2 3 4 A J Q ending with Enter.
EDIT
As OP wants undetermined length of input, I suggest to switch the input itself from char to std::string.
This way access is gained to more intuitive and effective I\O operations:
#include <iostream> // std::cin, cout, endl
#include <string> // std::string: can omit this line
#include <cctype> // isspace(): can omit
int main(){
int count = 0;
std::string currcard{""};
std::cout << "Enter cards seen on table: "<< std::endl;
std::getline(std::cin, currcard);
for (char c : currcard) {
if (isspace(c))
continue;
switch (c) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
++count;
break;
case '7':
case '8':
case '9':
break;
case 'A':
case 'J':
case 'Q':
case 'K':
--count;
break;
default:
//std::cout << "Invalid Entry\n";
break;
}
}
std::cout <<"Current count: "<< count << std::endl;
//user enter cards seen on table and if below 7 increment
//based on count the program returns if you should hit or quit
return 0;
}
Notice I have added a check for white spaces, and removed the message for invalid entries: both simply get ignored. But if needed that line can be uncommented.
Old solution
You can use cin.getline() as suggested in the comments, in conjunction with a flag that triggers exit from the loop once three inputs are given:
#include <iostream>
int main(){
static int count = 0, flag = 0;
char currcard;
std::cout << "Enter cards seen on table: "<< std::endl;
while(std::cin.getline(&currcard, 3)){
switch (currcard)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
++count;
break;
case '7':
case '8':
case '9':
break;
case 'A':
case 'J':
case 'Q':
case 'K':
--count;
break;
default:
std::cout << "Invalid Entry\n";
--flag;
break;
}
++flag;
if (flag == 3)
break;
}
std::cout <<"Current count: "<< count << std::endl;
//user enter cards seen on table and if below 7 increment
//based on count the program returns if you should hit or quit
return 0;
}
There is also a flag decrement for invalid entries.

How do I split a string by character? C++

I'm working on a fun random ICAO translator program and I'm almost done with it but I'm having one little problem. How do I go about splitting a string by each character? For example the output I want is;
The word mike translated in the ICAO alphabet is:
m: Mike
i: Indiana
k: Kilo
e: Echo
So far I just get;
The word mike translated in the ICAO alphabet is:
Mike
Indiana
Kilo
Echo
Apparently my post is mostly code and I must add more detail so I'm adding this sentence to hopefully satisfy the requirements. Also the translation should be right on top of each other and not one extra space down. I'm having problems with that and idk how to fix that.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word = " ", phonetic;
int count = 0;
cout << "Enter a word: ";
cin >> word;
while(count < word.length())
{
switch(word.at(count))
{
case 'A': case 'a': phonetic += " Alpha\n";
break;
case 'B': case 'b': phonetic += " Bravo\n";
break;
case 'C': case 'c': phonetic += " Charlie\n";
break;
case 'D': case 'd': phonetic += " Delta\n";
break;
case 'E': case 'e': phonetic += " Echo\n";
break;
case 'F': case 'f': phonetic += " Foxtrot\n";
break;
case 'G': case 'g': phonetic += " Golf\n";
break;
case 'H': case 'h': phonetic += " Hotel\n";
break;
case 'I': case 'i': phonetic += " Indiana\n";
break;
case 'J': case 'j': phonetic += " Juliet\n";
break;
case 'K': case 'k': phonetic += " Kilo\n";
break;
case 'L': case 'l': phonetic += " Lima\n";
break;
case 'M': case 'm': phonetic += " Mike\n";
break;
case 'N': case 'n': phonetic += " November\n";
break;
case 'O': case 'o': phonetic += " Oscar\n";
break;
case 'P': case 'p': phonetic += " Papa\n";
break;
case 'Q': case 'q': phonetic += " Quebec\n";
break;
case 'R': case 'r': phonetic += " Romeo\n";
break;
case 'S': case 's': phonetic += " Sierra\n";
break;
case 'T': case 't': phonetic += " Tango\n";
break;
case 'U': case 'u': phonetic += " Uniform\n";
break;
case 'V': case 'v': phonetic += " Victor\n";
break;
case 'W': case 'w': phonetic += " Whiskey\n";
break;
case 'X': case 'x': phonetic += " X-Ray\n";
break;
case 'Y': case 'y': phonetic += " Yankee\n";
break;
case 'Z': case 'z': phonetic += " Zulu\n";
break;
default: cout << "You did not enter a name" << endl;
}
count++;
}
cout << "The word "<< word <<" in the ICAO alphabet is:\n"
<< phonetic << endl;
return 0;
}
To go through a string, you can simply use iterators:
std::string test_string = "test";
for( auto const& character : test_string )
{
std::cout << character << "\n";
}
The whole program can be simplified, by using a map:
// Example program
#include <iostream>
#include <map>
#include <string>
char to_lower(char ch)
{
return static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
int main()
{
const std::map<char, std::string> phonetic_alphabet =
{
{'a', "Alpha"}
,{'b', "Bravo"}
,{'c', "Charlie"}
,{'d', "Delta"}
,{'e', "Echo"}
,{'f', "Foxtrot"}
,{'g', "Golf"}
,{'h', "Hotel"}
,{'i', "Indiana"}
,{'j', "Julia"}
,{'k', "Kilo"}
,{'l', "Lima"}
,{'m', "Mike"}
,{'n', "November"}
,{'o', "Oscar"}
,{'p', "Papa"}
,{'q', "Quebec"}
,{'r', "Romeo"}
,{'s', "Sierra"}
,{'t', "Tango"}
,{'u', "Uniform"}
,{'v', "Victor"}
,{'w', "Whiskey"}
,{'x', "X-Ray"}
,{'y', "Yankee"}
,{'z', "Zulu"}
};
std::cout << "Enter a word: ";
std::string word;
std::cin >> word;
for( auto const& c : word )
{
const char lower_c = to_lower(c);
if( phonetic_alphabet.find(lower_c) != phonetic_alphabet.end() )
{
std::cout << phonetic_alphabet.at(lower_c) << " ";
}
else
{
std::cout << c << " ";
}
}
}
If I understand your post correctly, you don't want to split a string but to iterate through its characters.
In C++11:
for (char& c : word) {
// switch (c)
}
The answer of infinitezero is totally ok and probably the best solution in this case.
I would like to addtionally show a loop-less solution, also based on a std::unordered_map and able to read a complete sentence.
The basic idea is: Based on the requirement to transform single characters to ICAOwords, I decided to use a dedicated function for this purpose: std::transform. You may see the documentation here
Please see the additional / alternative solution below:
#include <iostream>
#include <unordered_map>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
// Preinitialize an unordered map
std::unordered_map<int, std::string> alpha =
{
{'a', "Alpha"},{'b', "Bravo"},{'c', "Charlie"},{'d', "Delta"},{'e', "Echo"},{'f', "Foxtrot"},{'g', "Golf"},
{'h', "Hotel"},{'i', "Indiana"},{'j', "Julia"},{'k', "Kilo"},{'l', "Lima"} ,{'m', "Mike"},{'n', "November"},
{'o', "Oscar"},{'p', "Papa"},{'q', "Quebec"},{'r', "Romeo"},{'s', "Sierra"},{'t', "Tango"},{'u', "Uniform"},
{'v', "Victor"},{'w', "Whiskey"},{'x', "X-Ray"},{'y', "Yankee"},{'z', "Zulu"}};
// Read word form user
if (std::string word; std::getline(std::cin, word)) {
// Show output to user
std::cout << "\n\n" << word << " --> ";
// Convert and show
std::transform(word.begin(), word.end(), std::ostream_iterator<std::string>(std::cout, " "),
[&](const char c) { return (isalpha(c) ? alpha[tolower(c)] : ""); });
}
return 0;
}

C++ program to convert string to numeric digits

I'm trying to create a function that converts input words to numeric digits like a mobile numpad. It is for an assignment. I cannot use cstring or character arrays.
Can someone please identify and correct the error in my code? It currently gives the error: ISO C++ forbids comparison between pointer and integer [-fpermissive].
I am not using any pointer variables. I do have used the strlen() function to determine the exact place of a character in a string. Any help is greatly appreciated.
#include<iostream>
#include<conio.h>
#include<string.h>
#include<stdio.h>
using namespace std;
void Letter_correspondence();
int main()
{
Letter_correspondence();
return 0;
}
void Letter_correspondence()
{
cout<<"Enter the letters of the word you want to convert to numbers: ";
char a[]="Hello";
char b[]="world";
int len=strlen(a);
int lenb=strlen(b);
int n;
int l=a[n];
for (n=0;n<=7;n++)
{
while (n<=len)
{
if (l=="a"||l=="b"||l=="c")
{
if (n==2)
{
cout<<"-";
}
cout<<"2";
}
else if (l=="d"||l=="e"||l=="f")
{
if (n==2)
{
cout<<"-";
}
cout<<"3";
}
else if (l=="g"||l=="h"||l=="i")
{
if (n==2)
{
cout<<"-";
}
cout<<"4";
}
else if (l=="j"||l=="k"||l=="l")
{
if (n==2)
{
cout<<"-";
}
cout<<"5";
}
else if (l=="m"||l=="n"||l=="o")
{
if (n==2)
{
cout<<"-";
}
cout<<"6";
}
else if (l=="p"||l=="q"||l=="r"||l=="s")
{
if (n==2)
{
cout<<"-";
}
cout<<"7";
}
else if (l=="t"||l=="u"||l=="v")
{
if (n==2)
{
cout<<"-";
}
cout<<"8";
}
else if (l=="w"||l=="x"||l=="y"||l=="z")
{
if (n==2)
{
cout<<"-";
}
cout<<"9";
}
}
}
}
If I understood this right, you're trying to map characters to different ones and print them. You said you cannot use cstring or character arrays, but you do that here:
char a[]="Hello";
char b[]="world";
Instead, I would just use std::string:
std::string a = "Hello";
You can then iterate through it using a range-based for loop. The best way to print your string would probably be using a switchstatement:
for (char &c : a)
{
switch (tolower(c)) {
case 'a':
case 'b':
case 'c':
std::cout << 2;
break;
case 'd':
case 'e':
case 'f':
std::cout << 3;
break;
case 'g':
case 'h':
case 'i':
std::cout << 4;
break;
case 'j':
case 'k':
case 'l':
std::cout << 5;
break;
case 'm':
case 'n':
case 'o':
std::cout << 6;
break;
case 'p':
case 'q':
case 'r':
case 's':
std::cout << 7;
break;
case 't':
case 'u':
case 'v':
std::cout << 8;
break;
case 'w':
case 'x':
case 'y':
case 'z':
std::cout << 9;
break;
default:
std::cout << c;
}
}
If you're using an old version of C++ that doesn't support range based for loops, change this
for (char &c : a)
{
switch (tolower(c)) {
To this
for (size_t i = 0; i < a.size(); i++)
{
switch (tolower(a[i])) {
And std::cout << c; to std::cout << a[i];.

C++ Digital Calculator Simulator

I'm currently stuck on having to write a simulator for a real, old calculator (like those one dollar calculators, the ones with the buttons, in which you must enter your numbers one push-of-a-button at a time, can't write the Whole number directly and for now it is only in integers). I know for sure that there has to be a switch case for the 0-9 and one for the operators (including '='). Should break the cycle and print the result of the calculation, but I can use as many operators as I want in the each "session" (ex: 123+7-89/6*8+3). I am finding trouble in connecting the two loops and in printing the result. Thank you so much in advance.
#include <iostream>
using namespace std;
int execute(int n1, int n2, char c);
int main()
{
int acc, num=0;
char c, op;
cin>>c;
while (1) {
switch (c) {
case '0': cout << "0";
case '1': cout << "1";
case '2': cout << "2";
case '3': cout << "3";
case '4': cout << "4";
case '5': cout << "5";
case '6': cout << "6";
case '7': cout << "7";
case '8': cout << "8";
case '9': cout << "9";
num=num*10+static_cast<int>(c-'0');
acc=num;
op=c;
acc= execute(acc, num, op);
}
}
return 0;
}
int execute(int n1, int n2, char c) {
do {
switch (c) {
case '+': return (n1+n2);
case '-': return (n1-n2);
case '*': return (n1*n2);
case '/': return (n1/n2);
case '=': return true;
}
} while (!'=')
}

Iterating through a string, and switch statements: C++

I was writing some code, and came across some trouble. I wanted to write a function that checks if a string has any vowels, and tried to do it through a for loop with a switch statement inside. Apparently, it doesn't work and never returns true for some reason.
bool scanStr(string userInp) {
for (int i = 0; i < userInp.size(); i++) {
switch (userInp[i])
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
case 'y':
case 'Y':
return true;
break;
default:
return false;
}
}
}
I tried just testing if the program was actually iterating through the string, and it was, so I don't understand why in the function, it always returns false?
int main() {
string userInp;
string pigLatin;
cout << "Please enter a string to convert to pig Latin: " << endl;
cin >> userInp;
cout << endl;
// tests
for (int i = 0; i < userInp.size(); i++) { //checking if it actually iterates
cout << userInp[i];
}
cout << endl;
if (scanStr(userInp))
cout << "it has a vowel" << endl;
else
cout << "no vowel" << endl;
system("pause");
return 0;
}
At first I thought that it was because the loop kept on continuing even though there was a break statement after the last case, but I'm not entirely sure if that is the reason.
Any ideas?
I would suggest that you extract the logic of vowel testing into its own function:
bool is_vowel(char x)
{
switch (x)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
case 'y':
case 'Y':
return true;
default:
return false;
}
}
Then you can use a standard algorithm instead of a loop:
#include <algorithm>
#include <string>
bool contains_vowel(const std::string& str)
{
return std::any_of(str.begin(), str.end(), is_vowel);
}
(I renamed scanStr to contains_vowel because that name is much more descriptive.)
Drop this lines from your function:
default:
return false;
They make your function return false on the first non-vowel it encounters.
You only want to return false if you reach the end of the loop and haven't returned true yet.
bool scanStr(string userInp)
{
for (int i = 0; i < userInp.size(); i++)
{
switch (userInp[i])
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
case 'y':
case 'Y':
return true;
}
}
return false;
}
A better approach in modern C++ would be:
bool scanStr(const std::string& userInp)
{
for (const auto c : userInp)
{
switch (c)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
case 'y':
case 'Y':
return true;
}
}
return false;
}
But if you don't know what it means, don't worry about it now, your book or tutorial will explain soon enough.
Problem was, if any character wasn't vowel, that function imediatelly returned false. Also use const &. const allows you to pass const strings and reference saves some time, because C++ doesn't have to copy whole string.
bool scanStr(const string & userInp) {
for (int i = 0; i < userInp.size(); i++) {
switch (userInp[i])
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
case 'y':
case 'Y':
return true;
break;
}
}
return false;
}
First the compiler will turn the switch case into a lookup table, then auto will be decided as a data-type by the compiler based on the value assigned (in this case it's char).
Or just give it to your compiler, it knows how to do it.
bool scanStr(string userInp)
{
for(auto c : userInp)
{
switch (c)
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
case 'y': case 'Y':
return true;
}
}
return false;
}