error in character comparison - c++

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

Related

whats wrong with this code it just give Enter an Alphabet= j ERROR! (Enter one Alphabet only not two Alphabet or a number)

#include <stdio.h>
int main(void)
{
char a;
printf("Enter an Alphabet=\n");
scanf("%c",&a);
if(a>=0)
{
printf("ERROR!\n(Enter one Alphabet only not two Alphabet or a number)");
}
else
{
switch (a)
{
case 'a' :
printf("It is vowel");
break;
case 'e' :
printf("It is vowel");
break;
case 'i' :
printf("It is vowel");
break;
case 'o' :
printf("It is vowel");
break;
case 'u' :
printf("It is vowel");
break;
default :
printf("it is a constant");
}
}
return 0;
}
this code just give this result
Enter an Alphabet=
r
ERROR!
(Enter one Alphabet only not two Alphabet or a number)
--------------------------------
Process exited after 2.259 seconds with return value 0
Press any key to continue . . .
To check if a character is an alphabetical character, you should use the isalpha function.
Putting together my other pointer (checking what scanf returns as well as using tolower, the code could be written something like this:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char a;
printf("Enter an alphabetical character: ");
if (scanf(" %c", &a) != 1)
{
printf("Error reading input\n");
return 1;
}
if (!isalpha(a))
{
printf("Character is not an alphabetical character\n");
return 1;
}
switch (tolower(a))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("It's a vowel\n");
break;
default:
printf("It's a consonant\n");
break;
}
}
[Note that the above code is still written in plain C, not C++]

converting char to double in switch statement

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

Getting input X/X/etc with char X and separating it with slash /

I make program build with C++. My program is convert binary to decimal and the decimal convert to alphabet. The input is separated with slash "/"
input example :
input : 00001/00010/00011
output : abc
this is my code
#include <iostream>
#include <conio.h>
#include <cstring>
using namespace std;
int main()
{
char X[64];
int T,d=0,i=0,j;
scanf("%[^/]/%d", X);
while(X[i]!=0)
{ if(X[i]=='0'||X[i]=='1')
{
d=d*2+X[i]-48;
}i++;
}
switch (d)
{
case 1:
cout<<"a";
break;
case 2:
cout<<"b";
break;
case 3:
cout<<"c";
break;
case 4:
cout<<"d";
break;
case 5:
cout<<"e";
break;
case 6:
cout<<"f";
break;
case 7:
cout<<"g";
break;
case 8:
cout<<"h";
break;
case 9:
cout<<"i";
break;
case 10:
cout<<"j";
break;
case 11:
cout<<"k";
break;
case 12:
cout<<"l";
break;
case 13:
cout<<"m";
break;
case 14:
cout<<"n";
break;
case 15:
cout<<"o";
break;
case 16:
cout<<"p";
break;
case 17:
cout<<"q";
break;
case 18:
cout<<"r";
break;
case 19:
cout<<"s";
break;
case 20:
cout<<"t";
break;
case 21:
cout<<"u";
break;
case 22:
cout<<"v";
break;
case 23:
cout<<"w";
break;
case 24:
cout<<"x";
break;
case 25:
cout<<"y";
break;
case 26:
cout<<"z";
break;
}
cout << endl;
}
I have used a number of ways that are still unable, and only the front binary can be read.
Sorry for my bad english
There are two immediate problems you need to fix:
scanf("%[^/]/%d", X);
As written, this will exhibit undefined behavior, since it'll try and parse the first string into X, then it reads the '/' that separates, but then it'll read the next set of digits as a number without a variable to store them in. I'd advise getting rid of the trailing %d in the format specifier string.
You should also check the return value of scanf() since that will tell you how many values were parsed. Knowing this leads very neatly into the solution to the main problem: why is it only processing the first number?
That's because you call scanf() once, read on number, process it, output the result, and then terminate execution.
What you need to do is wrap up most of the code in a while loop, and use the following line as the test condition for the loop:
while (scanf("%[^/]/", X) == 1)
That kills two birds with one stone: it'll correctly parse the next set of digits and enter the loop if it finds anything, and if there isn't anything, it should return 0, causing the loop to terminate.
#include <iostream>
#include <string>
#include <sstream>
template< typename T, std::size_t N >
std::size_t sizeof_array(T (&)[N]) { return N; }
int main()
{
std::string str;
std::getline(std::cin, str);
int number[3]{};
std::size_t pos;
auto start = str.data();
for (std::size_t i{}; i < sizeof_array(number); ++i) {
number[i] = std::stoi(start, &pos, 2);
start += pos + 1;
}
for (auto n : number)
std::cout << static_cast<char>('A' + n - 1);
std::cout.put('\n');
}

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.

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