C++ program to convert string to numeric digits - c++

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];.

Related

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 (!'=')
}

Convert Hex To Binary Function Adding Extra Values

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

creating complement of DNA sequence and reversing it C++

So I am trying to create the complement of the sequence
TGAGACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTGC
however my output didn't work as expected.
The complements for each letter in the sequence are
A -> T
G -> C
C -> G
T -> A
I've been programming in Java for over a year now so I've gotten really rusty with pointers in C++, I'm guessing the problem lies in the reverse methods and the way to pointers are shifted around through each pass of the function call
#include<stdio.h>
#include<iostream>
using namespace std;
void reverse(char s[]);
int main() {
char s[40] = {'T','G','A','G','A','C','T','T','C','A','G','G','C','T','C','C','T','G','G','G','C','A','A','C','G','T','G','C','T','G','G','T','C','T','G','T','G','T','G'};
cout << "DNA sequence: "<< endl << s << endl;
reverse(s);
cout << "Reverse Compliment: "<< endl << s << endl;
system("pause");
}
void reverse(char s[])
{
char c;
char *p, *q;
p = s;
if (!p)
return;
q = p + 1;
if (*q == '\0')
return;
c = *p;
reverse(q);
switch(c) {
case 'A':
*p = 'T';
break;
case 'G':
*p = 'C';
break;
case 'C':
*p = 'G';
break;
case 'T':
*p = 'A';
break;
}
while (*q != '\0') {
*p = *q;
p++;
q++;
}
*p = c;
return;
}
Standard modern C++ makes this low-level, pointer-oriented programming, unnecessary (in fact, you're effectively writing C).
Once you have a function, say complement, which transforms a nucleotide to its complement, you just need to apply some standard library function like transform.
Here is a rewrite of your program in C++11:
#include <string>
#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
char complement(char n)
{
switch(n)
{
case 'A':
return 'T';
case 'T':
return 'A';
case 'G':
return 'C';
case 'C':
return 'G';
}
assert(false);
return ' ';
}
int main()
{
string nucs = "ACAATTGGA";
transform(
begin(nucs),
end(nucs),
begin(nucs),
complement);
cout << nucs << endl;
}
std::string style, looks easy and clean: I presume it may be useful to OP or others.
creating complement of DNA sequence and reversing it C++
In other words, it is reverse complement of a DNA sequence, which can be easily achieved by reversing the DNA sequence and then getting its complement. Or getting the complement and then reversing. An example is shown below.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string DNAseq = "TGAGACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTGC";
reverse(DNAseq.begin(), DNAseq.end());
for (std::size_t i = 0; i < DNAseq.length(); ++i){
switch (DNAseq[i]){
case 'A':
DNAseq[i] = 'T';
break;
case 'C':
DNAseq[i] = 'G';
break;
case 'G':
DNAseq[i] = 'C';
break;
case 'T':
DNAseq[i] = 'A';
break;
}
}
std::cout << "reverse complement : " << DNAseq << std::endl;
return 0;
}
Change the reverse method like this
void reverse(char s[])
{
while (*s) {
switch(*s) {
case 'A':
*s = 'T';
break;
case 'G':
*s = 'C';
break;
case 'C':
*s = 'G';
break;
case 'T':
*s = 'A';
break;
}
++s;
}
return;
}
...and you will get correct result.
If you don't like pointers, please, don't use them! In modern C++ pointers aren't often necessary. The following code is C++11 (do you have C++11 compiler?) written as I would do it.
#include <string>
#include <iostream>
#include <algorithm>
std::string reverse(std::string seq)
{
auto lambda = [](const char c) {
switch (c) {
case 'A':
return 'T';
case 'G':
return 'C';
case 'C':
return 'G';
case 'T':
return 'A';
default:
throw std::domain_error("Invalid nucleotide.");
}
};
std::transform(seq.cbegin(), seq.cend(), seq.begin(), lambda);
return seq;
}
int main()
{
std::string seq("TGAGACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTG");
std::cout << "DNA sequence: " << std::endl << seq << std::endl;
seq = reverse(seq);
std::cout << "Reverse Compliment: " << std::endl << seq << std::endl;
system("pause");
return EXIT_SUCCESS;
}
Some notes:
Use default in switch statement.
In C++ it's better to return a value from a function than to manipulate a variable via pointer.
Prefer std::string to plain char.

default is not working on my switch (c++)

My problem it's very simple to explain, but I have no idea to solve it.
In my switch statement in the code that you can see below, the default case does not work, but if I remove the last return ""; works fine.
Like something so simple can lead a person to the path of bitterness?
Greetings and thank you very much in advance
QString sim900::loop() {
QString text = readSerial();
if (text != "")
{
QStringList commands;
// 0 1 2 3 4 5
commands << "+RECEIVE" << " CLOSED" << "REMOTE IP: " << "+CMTI: " << "+CSQ: " << "+CIPSEND=";
for (int n=0; n<commands.length(); n++)
{
if (text.indexOf(commands[n]) != -1)
switch (n)
{
case 0:
SocketReceive(text, false);
break;
case 1:
DropClient(text);
break;
case 2:
NewClient(text);
break;
case 3:
break;
case 4:
EstadoRed(text);
break;
case 5:
ReadyToSend(text);
break;
default:
if (n == commands.length()-1)
return text;
}
}
}
return "";
}
Consider this...
for(int n = 1; n < 2; ++n) {
switch (n) {
case 0:
break;
default:
std::cout << "Whoops!";
}
}
this will print "Whoops!" once. That's because I start outside the cases which I handle - a default case.
Now, consider this...
int commandsLength = 6;
for(int n = 0; n < commandsLength; ++n) {
switch (n) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
if (n == commandsLength - 1)
std::cout << "Whoops!";
}
}
and the fact the default case can never be reached because I handle the 5 case and due to the condition on the for n cannot be >= 6. This is the situation you've created for yourself.

Error C2679: binary '+' : no operator found which takes a right-hand operand of type

First up, yes, this is homework that I'm struggling with, so help would be appreciated. We're making a calculator in C++ that is supposed to function differently on the + and - operators.
With '+' it is supposed to to add the two numbers together (i.e., 45 + 54 = 4554).
With '-' it is supposed to remove the first digit of the first element from the second element (i.e., 1217 - 1 = 27) We're supposed to do this by overloading the + and - operators, which I seem to be struggling with. Thanks in advance for the help!
class WhackyRPN
{
public:
int value;
int operator+ (WhackyRPN a[]);
int operator- (WhackyRPN s[]);
int getValue();
void setValue(int);
};
void WhackyRPN::setValue(int val){
value = val;
}
int WhackyRPN::getValue(){
return value;
}
int WhackyRPN::operator+ (WhackyRPN a[]){
string combinedNum = to_string(a[1].getValue()) + to_string(a[0].getValue());
int finalNum = stoi(combinedNum);
return finalNum;
}
int WhackyRPN::operator- (WhackyRPN s[]){
int minusNum;
string firstNum = to_string(s[0].getValue());
string secondNum = to_string(s[1].getValue());
string minusString = to_string(minusNum);
for (int i = 0; i < firstNum.length(); i++){
if (firstNum.at(0) != secondNum.at(i)){
minusString.at(i) += secondNum.at(i);
}
}
minusNum = stoi(minusString);
return minusNum;
}
int main()
{
WhackyRPN stackPos[4];
string indent = " ";
string userInput;
stackPos[0].setValue(0);
stackPos[1].setValue(0);
stackPos[2].setValue(0);
stackPos[3].setValue(0);
while (1){
system("cls");
cout << "---STACK---" << endl;
cout << indent << stackPos[3].getValue() << endl;
cout << indent << stackPos[2].getValue() << endl;
cout << indent << stackPos[1].getValue() << endl;
cout << indent << stackPos[0].getValue() << endl;
cout << "CMD: ";
cin >> userInput;
if (userInput == "exit" || userInput == "Exit" || userInput == "EXIT"){
exit(0);
}
switch (userInput[0]){
case 'q':
case 'Q':
exit(0);
case 'p':
case 'P':
stackPos[0] = stackPos[1];
stackPos[1] = stackPos[2];
stackPos[2] = stackPos[3];
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(stoi(userInput));
break;
case '+': //combine pos[1] and pos[0];
int finalNum = stackPos[1] + stackPos[0];
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(finalNum);
break;
case '-': //remove pos[0].firstNum from pos[1]
int minusNum = stackPos[0] - stackPos[1];
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(minusNum);
break;
case '/': //divide pos[1] by pos[0]
if (stackPos[0].getValue() == 0){
cout << "Cannot divide by 0" << endl;
system("pause");
break;
}
int endQuotient = stackPos[1].getValue() / stackPos[0].getValue();
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(endQuotient);
break;
case '*': //multiply pos[1] by pos[0]
int endProduct = stackPos[1].getValue() * stackPos[0].getValue();
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(endProduct);
break;
default:
break;
}
}
system("pause");
return 0;
}
You get the error that you do because there really is no overload of operator+ which stackPos[1] + stackPos[0] could resolve to. The only overload you have is of type WhackyRPN::operator+(WhackyRPN*);(it is a pointer even though you have written an array - read here and here. But that isn't relevant to this question.) The signature should be WhackyRPN::operator+(WhackyRPN). More idiomatic would be WhackyRPN::operator+(const WhackyRPN&). For more, read this great answer.
replace
int finalNum = stackPos[1] + stackPos[0];
with
int finalNum = stackPos[1].getValue() + stackPos[0].getValue();
In your program, you have the array of objects stackPos[], which has functions setValue() and getValue() which take and return integer respectively. You need to use getValue() here as the array elements themselves are not integer, they are objects.
This is exactly what your error statement is saying as well. But you seem to already know that because you have implemented it in * and / operations.
Hope this helps.