converting char to double in switch statement - c++

I'm quite confused with this question. Can anyone enlighten me?
The question is:
Write a function that converts a char letter grade into its numerical equivalent. Use the grading system below. A=4.0 B=3.0 C=2.0 D=1.0 F=0.0
To receive full credit your answer must use a switch statement. In case when the function receives a character that is not A,B,C,D,F, return value 0.0. The prototype is below:
double gradeNum(char grade)
{ //your code here
//This is my coding
#include<iomanip>
#include<iostream>
#include<string>
using namespace std;
double gradeNum(char grade);
int main ()
{
char grade;
cout<<"Please enter your grade;"<<endl;
cin>>grade;
double output=gradeNum(grade);
cout<<output;
return 0;
}
double gradeNum(char grade){
switch (grade){
case 'A':
return 4.0;
break;
case 'B':
return 3.0;
break;
case 'C':
return 2.0;
break;
case 'D':
return 1.0;
break;
case 'F':
return 0.0;
break;
default:
return 0.0;
break;
}
}

The switch statement should be in the function "gradeNum()".
From main you should call the above function with a specific input. For example:
int main()
{
...
double output = gradeNum('A');
...
}
double gradeNum(char grade)
{
switch (grade)
{
case 'A':
return 4.0;
case 'B':
return 3.0;
....
}
}

Related

Evaluation of Postfix Expression using stl in c++

I don't what is wrong with this code it should answer -4
but the answer i'm getting is 2492
#include <bits/stdc++.h>
using namespace std;
int main() {
stack <int> st;
char s[]="231*+9-" ;
for(int i=0;i<7;i++){
if (isdigit(s[i])){
st.push((int)s[i]);
}
else{
float val1,val2;
val1=st.top();
st.pop();
val2=st.top();
st.pop();
switch (s[i])
{
case '+': st.push( val2 + val1); break;
case '-': st.push(val2 - val1); break;
case '*': st.push( val2 * val1); break;
case '/': st.push( val2/val1); break;
}
}
}int m=st.top();
cout<<m;
return 0;
}
You cannot cast a numeric char directly to int if you want its digit value, because that would just give its ASCII code. Instead, do st.push((int)(s[i]-'0')). This removes the offset of the 0-9 character group.
One easy way is to replace char s[]="231*+9- by a string string s ="231*+9-"
and then create an alias of size_t, so you can push the char as a substr like this:
std::string::size_type sz;
...
st.push(stoi(s.substr(i,1), &sz));

c++ An interesting result [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 6 years ago.
Improve this question
This code somehow always adds to the conclusion 12142.
For example insert 12; the output is 1212142, insert 1 + 2; get 312142
#include "stdafx.h"
#include <iostream>
using namespace std;
class Token
{
public:
char kind;
double value;
};
class Token_stream
{
public:
Token get();
void putback(Token t);
private:
bool full{ false };
Token buffer;
};
void Token_stream::putback(Token t)
{
buffer = t;
full = true;
}
Token Token_stream::get()
{
if (full)
{
full = false;
return buffer;
}
char ch;
cin >> ch;
switch (ch)
{
case ';':
case 'q':
case '(': case ')': case '+':
case '-': case '*': case '/':
return Token{ ch };
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
cin.putback(ch);
double val;
cin >> val;
return Token{ '8',val };
}
default:
throw runtime_error("dont true token");
break;
}
}
Token_stream ts;
double expres();
double prim()
{
Token t = ts.get();
switch (t.kind)
{
case '(':
{
double d = expres();
t = ts.get();
if (t.kind != ')')
{
throw runtime_error("))))");
}
return d;
}
case '8':
return t.value;
default:
throw runtime_error("perm");
}
}
double term()
{
double left = prim();
Token t = ts.get();
while (true)
{
switch (t.kind)
{
case '*':
left *= prim();
t = ts.get();
break;
case '/':
{
double d = prim();
if (d == 0)
{
throw runtime_error("/0");
}
left /= d;
t = ts.get();
break;
}
default:
ts.putback(t);
return left;
}
}
}
double expres()
{
{
double left = term();
Token t = ts.get();
while (true)
{
switch (t.kind)
{
case '+':
left += term();
t = ts.get();
break;
case '-':
left -= term();
t = ts.get();
break;
default:
ts.putback(t);
return left;
}
}
}
}
int main()
{
double val = 0;
while (cin)
{
Token t = ts.get();
if (t.kind == 'q') break;
if (t.kind == ';')
cout << "=" << val << '/n';
else
ts.putback(t);
val = expres();
}
return 0;
}
This code is taken from the book Programming - Principles and Practice Using C ++
Look here:
if (t.kind == ';')
cout << "=" << val << '/n';
'/n' is the character / followed by the character n, squeezed into what's known as a "multi-character literal". These are actually ints with implementation-defined values; on your system, apparently that's the number 12142.
You meant the single character '\n'.
In future, locate and solve problems like this by constructing a minimal testcase. In doing so, you would eventually have ended up with a test program that simply said cout << '/n' and output 12142; at that point, if you still didn't spot the typo, you'd have a very simple thing to look up and/or ask about.

New to c/c++ an confused with pointers

I'm fairly new to c/c++ programming and currently I'm working on some basic programms to get in touch with the language. My newest programm is a simple hex_xor function, that follows the instruction of Cryptopals Challenge 2. But I'm already getting errors and I'm assuming I am doing something horribly wrong with the pointers I am using.
Here is a part of my programm:
const char* hex_char_to_bin(char c)
{
switch(toupper(c))
{
case '0': return "0000";
case '1': return "0001";
case '2': return "0010";
case '3': return "0011";
case '4': return "0100";
case '5': return "0101";
case '6': return "0110";
case '7': return "0111";
case '8': return "1000";
case '9': return "1001";
case 'A': return "1010";
case 'B': return "1011";
case 'C': return "1100";
case 'D': return "1101";
case 'E': return "1110";
case 'F': return "1111";
}
}
const char* hex_binary(const char* c){
std::string result = "";
for(int i = 0; i < strlen(c); i++){
result += hex_char_to_bin(c[i]);
}
return result.c_str();
}
int main(){
std::string s1 = "1c0111001f010100061a024b53535009181c";
std::string s2 = "686974207468652062756c6c277320657965";
const char* bin1 = hex_binary(s1.c_str());
const char* bin2 = hex_binary(s2.c_str());
std::cout << bin1 << "\n" << bin2 << std::endl;
return 0;
}
The output is the following:
011010000110100101110100001000000111010001101000011001010010000001100010011101010110110001101100001001110111001100100000011001010111100101100101
011010000110100101110100001000000111010001101000011001010010000001100010011101010110110001101100001001110111001100100000011001010111100101100101
In both variables (bin1/2) is the binary conversion of the second hex-string. My aim is (obviously) to have both binary-strings saved in different variables, so I can proceed with my xor-function. Can someone point out where I am failing to achieve my goal and why? Other hints are welcome aswell!
You can't use result of c_str() when main string object is no longer alive. So, you're referencing already freed resources and facing undefined behavior.
If I were you, I'd change hex_binary() to return std::string and just return result back without using c_str()

c++ The evaluation of expression. How to exit the while loop?

I use stack to evaluate an expression.
The most important function is below:
double Expression_Eval()
{
SeqStack<char,100> OPTR;
SeqStack<double,100> OPND;
OPTR.Push('#');
char ch;
ch=getchar();
while (ch!='#' || OPTR.GetTop()!='#')
{
if (!InOPTR(ch))
{
int n=ch-'0';
double num=(double)n;
OPND.Push(num);
ch=getchar();
}
else
{
char pre_op=OPTR.GetTop();
switch (Precede(pre_op, ch))
{
case '<': OPTR.Push(ch);
ch=getchar();
break;
case '=': OPTR.Pop();
ch=getchar();
break;
case '>': double b=OPND.Pop();
double a=OPND.Pop();
pre_op=OPTR.Pop();
OPND.Push(Operate(a, pre_op, b));
ch=getchar();
break;
}
}
}
return OPND.GetTop();
}
Then, when I input 8/(5-3)#, it will not print the result.
I think the loop termination condition ch!='#' || OPTR.GetTop()!='#' is wrong.
When I press Enter, getchar() get the last char is CR but not #.
But, I don't know how to revise it to make my program work.
The other part of my program is below:
#include<iostream>
using namespace std;
template<typename DataType,int StackSize>
class SeqStack
{
private:
DataType data[StackSize];
int top;
public:
SeqStack()
{ top=-1; }
~SeqStack() {}
void Push(DataType x)
{
if(top == StackSize-1)
throw "error";
data[++top]=x;
}
DataType Pop()
{
if(top == -1)
throw "error";
DataType x=data[top--];
return x;
}
DataType GetTop()
{
if(top != -1)
return data[top];
else
cout<<"error";
}
};
bool InOPTR(char ch)
{
if( (ch>='(' && ch<='+') || ch=='-' || ch=='/' )
{
return true;
}else{
return false;
}
}
char Precede(char op1, char op2)
{
char pri[7][7]={ {'>','>','<','<','<','>','>'}
, {'>','>','<','<','<','>','>'}
, {'>','>','>','>','<','>','>'}
, {'>','>','>','>','<','>','>'}
, {'<','<','<','<','<','=','#'}
, {'>','>','>','>','#','>','>'}
, {'<','<','<','<','<','#','='} };
int m,n;
switch(op1)
{
case '+': m=0;break;
case '-': m=1;break;
case '*': m=2;break;
case '/': m=3;break;
case '(': m=4;break;
case ')': m=5;break;
case '#': m=6;break;
}
switch(op2)
{
case '+': n=0;break;
case '-': n=1;break;
case '*': n=2;break;
case '/': n=3;break;
case '(': n=4;break;
case ')': n=5;break;
case '#': n=6;break;
}
return pri[m][n];
}
double Operate(double a, char op, double b)
{
double result;
switch(op)
{
case '+': result=a+b; break;
case '-': result=a-b; break;
case '*': result=a*b; break;
case '/': result=a/b; break;
}
return result;
}
int main()
{
double r=Expression_Eval();
cout<<r<<endl;
return 0;
}
Problem seem to be that '#' is considered a number, but it should be considered an operation:
Use:
bool InOPTR(char ch) {
if ((ch >= '(' && ch <= '+') || ch == '-' || ch == '/' || ch=='#'){
return true;
}
else {
return false;
}
}
Note that '#' is ASCII 64 which is not covered in the ranage '(' to '+' [40-43]
Hope this helps.
You need to consume carriage return or newline character after getchar(); which comes into play when you press enter button.
One trick is as below.
ch=getchar();
getchar(); //this getchar to consume CR.
since you have used ch = getchar() many times you have to use above solution at many places.
Better solution to this problem will be to enter string instead of entering single character using getchar()...
Hope you got what I am trying to say...

error in character comparison

after the switch statement the program compares the characters.in this phase ı have debugged and seen that the first character of string is 111 'o' instead of just 'o' and this causes my program to fail. how can I fix it or where is the problem?
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cmath>
using namespace std;
int main(){
char sentence1[50];
char sentence2[50];
int m,n,k,l;
int i,j,substitution;
cout<<"Enter the first word:"<<endl;
cin>>sentence1;
cout<<"Enter the second word:"<<endl;
cin>>sentence2;
m = strlen(sentence1);
n = strlen(sentence2);
int cost[m+1][n+1];
bool a1,a2;
cost[0][0]=0;
for(i=1;i<m+1;i++){
cost[i][0]=cost[i-1][0]+2;
}
for(j=1;j<n+1;j++){
cost[0][j]=cost[0][j-1]+2;
}
for(i=1;i<m+1;i++){
for(j=1;j<n+1;j++){
switch (sentence1[i-1]){
case 'a':a1=true;
case 'u':a1=true;
case 'e':a1=true;
case 'o':a1=true;
case 'i':a1=true;
default:a1=false;
}
switch (sentence2[j-1]){
case 'a':a2=true;
case 'u':a2=true;
case 'e':a2=true;
case 'o':a2=true;
case 'i':a2=true;
default:a2=false;
}
if(sentence1[i-1]==sentence2[j-1]){substitution=0;
}
else if(a1==true && a2==false){substitution=4;}
else if(a1==false && a2==true){substitution=4;}
else if(a1==true && a2==true){substitution=3;}
else if(a1==false && a2==false){substitution=3;}
cost[i][j]=min(min(cost[i-1][j]+2,cost[i][j-1]+2),cost[i-1][j-1]+substitution);
}
}
for(i=0;i<m+1;i++){
for(j=0;j<n+1;j++){
cout<<cost[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
switch statements "fallthrough" without a break.
switch (sentence1[i-1]){
case 'a':a1=true; break;
case 'u':a1=true; break;
case 'e':a1=true; break;
case 'o':a1=true; break;
case 'i':a1=true; break;
default:a1=false; break;
}
Since this logic is being repeated, consider promoting it to its own function.
bool is_a_vowel( char c )
{
switch (c){
case 'a':
case 'u':
case 'e':
case 'o':
case 'i':
return true;
default:
return false;
}
Now you can have more readable and consistent code.
a1 = is_a_vowel( sentence1[i-1] );
a2 = is_a_vowel( sentence2[j-1] );