Question

Code in c++ please fix all errors that’s being asked to find and please follow instructions...

Code in c++ please fix all errors that’s being asked to find and please follow instructions

-------------------------------------------------

// This is example code from Chapter 6.7 "Trying the second version" of
// "Software - Principles and Practice using C++" by Bjarne Stroustrup
//

/*
This file is known as calculator02buggy.cpp

I have inserted 5 errors that should cause this not to compile
I have inserted 3 logic errors that should cause the program to give wrong results

First try to find an remove the bugs without looking in the book.
If that gets tedious, compare the code to that in the book.

Happy hunting!

*/

#include "std_lib_facilities.h"

//------------------------------------------------------------------------------

lass Token {
public:
char kind; // what kind of token
double value; // for numbers: a value
Token(char ch) // make a Token from a char
:kind(ch), value(0) { }
Token(char ch, double val) // make a Token from a char and a double
:kind(ch), value(val) { }
};

//------------------------------------------------------------------------------

class Token_stream {
public:
Token_stream(); // make a Token_stream that reads from cin
Token get(); // get a Token (get() is defined elsewhere)
void putback(Token t); // put a Token back
private:
bool full; // is there a Token in the buffer?
Token buffer; // here is where we keep a Token put back using putback()
};

//------------------------------------------------------------------------------

// The constructor just sets full to indicate that the buffer is empty:
Token_stream::Token_stream()
:full(false), buffer(0) // no Token in buffer
{
}

//------------------------------------------------------------------------------

// The putback() member function puts its argument back into the Token_stream's buffer:
void Token_stream::putback(Token t)
{
if (full) error("putback() into a full buffer");
buffer = t; // copy t to buffer
full = true; // buffer is now full
}

//------------------------------------------------------------------------------

Token get()
{
if (full) { // do we already have a Token ready?
// remove token from buffer
full=false;
return buffer;
}

char ch;
cin >> ch; // note that >> skips whitespace (space, newline, tab, etc.)

switch (ch) {
case ';': // for "print"
case 'q': // for "quit"
case '(': case ')': case '+': case '-': case '*': case '/':
return Token(ch); // let each character represent itself
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '9':
{
cin.putback(ch); // put digit back into the input stream
double val;
cin >> val; // read a floating-point number
return Token('8',val); // let '8' represent "a number"
}
default:
error("Bad token");
}
}

//------------------------------------------------------------------------------

Token_stream ts; // provides get() and putback()

//------------------------------------------------------------------------------

double expression(); // declaration so that primary() can call expression()

//------------------------------------------------------------------------------

// deal with numbers and parentheses
double primary()
{
Token t = ts.get();
switch (t.kind) {
case '(': // handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected);
return d;
}
case '8': // we use '8' to represent a number
return t.value; // return the number's value
default:
error("primary expected");
}
}

//------------------------------------------------------------------------------

// deal with *, /, and %
double term()
{
double left = primary();
Token t = ts.get(); // get the next token from token stream

while(true) {
switch (t.kind) {
case '*':
left *= primary();
t = ts.get();
case '/':
{
double d = primary();
if (d == 0) error("divide by zero");
left /= d;
t = ts.get();
break;
}
default:
ts.putback(t); // put t back into the token stream
return left;
}
}
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the wrong code followed by the fixed code:

Q contains the wrong code and A contains the correct code where the correction is marked in bold.

===========================================================

Q:

lass Token {
public:
char kind; // what kind of token
double value; // for numbers: a value
Token(char ch) // make a Token from a char
:kind(ch), value(0) { }
Token(char ch, double val) // make a Token from a char and a double
:kind(ch), value(val) { }
};

A: class typo error:

class Token {
public:
    char kind;        // what kind of token
    double value;     // for numbers: a value
    Token(char ch)    // make a Token from a char
        :kind(ch), value(0) { }  
    Token(char ch, double val)     // make a Token from a char and a double
        :kind(ch), value(val) { }
};

===============================================================

Q:

class Token_stream {
public:
Token_stream(); // make a Token_stream that reads from cin
Token get(); // get a Token (get() is defined elsewhere)
void putback(Token t); // put a Token back
private:
bool full; // is there a Token in the buffer?
Token buffer; // here is where we keep a Token put back using putback()
};

A:

class Token_stream {
public:
Token_stream(); // make a Token_stream that reads from cin
Token get(); // get a Token (get() is defined in the below code segment)
void putback(Token t); // put a Token back
private:
bool full; // is there a Token in the buffer?
Token buffer; // here is where we keep a Token put back using putback()
};

============================================================

Q:

Token get()
{
if (full) { // do we already have a Token ready?
// remove token from buffer
full=false;
return buffer;
}

char ch;
cin >> ch; // note that >> skips whitespace (space, newline, tab, etc.)

switch (ch) {
case ';': // for "print"
case 'q': // for "quit"

case '(': case ')': case '+': case '-': case '*': case '/':
return Token(ch); // let each character represent itself
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '9':
{
cin.putback(ch); // put digit back into the input stream
double val;
cin >> val; // read a floating-point number
return Token('8',val); // let '8' represent "a number"
}
default:
error("Bad token");
}
}

A: Fixing the function type:

Token Token_stream::get(){
    if (full) {       // do we already have a Token ready?
        // remove token from buffer
        full=false;
        return buffer;
    }

    char ch;
    cin >> ch;    // note that >> skips whitespace (space, newline, tab, etc.)

    switch (ch) {
    case '=':    // for "print"
    case 'x':    // for "quit"
    case 'X':    // for "quit"
    case '(': case ')': case '+': case '-': case '*': case '/': case '%':
        return Token(ch);        // let each character represent itself
    case '.':
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
        {  
            cin.putback(ch);         // put digit back into the input stream
            double val;
            cin >> val;              // read a floating-point number
            return Token('8',val);   // let '8' represent "a number"
        }
    default:
        error("Bad token");
    }
}

==================================================================

Q:

double primary()
{
Token t = ts.get();
switch (t.kind) {
case '(': // handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected);
return d;
}
case '8': // we use '8' to represent a number
return t.value; // return the number's value
default:
error("primary expected");
}
}

A: Closing braces error:

double primary()
{
    Token t = ts.get();
    switch (t.kind) {
    case '(':    // handle '(' expression ')'
        {  
            double d = expression();
            t = ts.get();
            if (t.kind != ')') error("')' expected"); //<- Fixed the closing braces.
            return d;
        }
    case '8':            // we use '8' to represent a number
        return t.value; // return the number's value
    default:
        error("primary expected");
    }
}

===================================================================

Q:

double term()
{
double left = primary();
Token t = ts.get(); // get the next token from token stream

while(true) {
switch (t.kind) {
case '*':

left *= primary();
t = ts.get();
case '/':
{
double d = primary();
if (d == 0) error("divide by zero");
left /= d;

t = ts.get();
break;
}
default:
ts.putback(t); // put t back into the token stream
return left;
}
}
}

A: Added missing braces and logic for the missing cases.

double term()
{
    double left = primary();
    Token t = ts.get();        // get the next token from token stream

    while(true) {
        switch (t.kind) {
        case '*':
            {
            left *= primary();
            t = ts.get();
            break;
            }
        case '/':
            {  
                double d = primary();
                if (d == 0) error("divide by zero");
                left /= d;
                t = ts.get();
                break;
            }
        case '%':
            {
                int d = primary();
                int l = left;
                if (d == 0) error("divide by zero");
                left = l%d;
                t = ts.get();
                break;
            }
        default:
            ts.putback(t);     // put t back into the token stream
            return left;
        }
    }
}

Add a comment
Know the answer?
Add Answer to:
Code in c++ please fix all errors that’s being asked to find and please follow instructions...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Today assignment , find the errors in this code and fixed them. Please I need help...

    Today assignment , find the errors in this code and fixed them. Please I need help with find the errors and how ro fixed them. #include <iostream> #include <cstring> #include <iomanip> using namespace std; const int MAX_CHAR = 100; const int MIN_A = 90; const int MIN_B = 80; const int MIN_C = 70; double getAvg(); char determineGrade(double); void printMsg(char grade); int main() { double score; char grade; char msg[MAX_CHAR]; strcpy(msg, "Excellent!"); strcpy(msg, "Good job!"); strcpy(msg, "You've passed!"); strcpy(msg, "Need...

  • How to code up the postfixEval function using the instructions in the comments of the function?...

    How to code up the postfixEval function using the instructions in the comments of the function? // postfixEvalTest.cpp #include "Token.h" #include <iostream> #include <vector> #include <stack> using namespace std; // postfix evaluate function prototype double postfixEval(vector<Token> &expr); int main() { vector<Token> postfix; postfix.push_back(Token(VALUE,4.0)); postfix.push_back(Token(VALUE,3.0)); postfix.push_back(Token(VALUE,2.0)); postfix.push_back(Token(OPERATOR,'*')); postfix.push_back(Token(OPERATOR,'+')); postfix.push_back(Token(VALUE,18.0)); postfix.push_back(Token(VALUE,6.0)); postfix.push_back(Token(OPERATOR,'/')); postfix.push_back(Token(OPERATOR,'-')); double result = 0.0; //result = postfixEval(postfix); cout << "The result of 4 3 2 * + 18 6 / - .... is " << result << endl; vector<Token>...

  • The code will not run and I get the following errors in Visual Studio. Please fix the errors. err...

    The code will not run and I get the following errors in Visual Studio. Please fix the errors. error C2079: 'inputFile' uses undefined class 'std::basic_ifstream<char,std::char_traits<char>>' cpp(32): error C2228: left of '.open' must have class/struct/union (32): note: type is 'int' ): error C2065: 'cout': undeclared identifier error C2065: 'cout': undeclared identifier error C2079: 'girlInputFile' uses undefined class 'std::basic_ifstream<char,std::char_traits<char>>' error C2440: 'initializing': cannot convert from 'const char [68]' to 'int' note: There is no context in which this conversion is possible error...

  • Code in C++: Please help me fix the error in function: void write_account(); //function to write...

    Code in C++: Please help me fix the error in function: void write_account(); //function to write record in binary file (NOTE: I able to store data to a txt file but however the data get error when I try to add on data the second time) void display_all(); //function to display all account details (NOTE: This function is to display all the info that save account.txt which is ID, Name, and Type) void modify_account(int); //function to modify record of file...

  • This is C++ code for parking fee management program #include <iostream> #include <iomanip> using namespace std;...

    This is C++ code for parking fee management program #include <iostream> #include <iomanip> using namespace std; void input(char& car, int& ihour,int& imin, int& ohour, int& omin); void time(char car, int ihour, int imin, int ohour, int omin, int& phour, int& pmin, int& round, double& total); void parkingCharge (char car, int round, double& total); void print(char car, int ihour, int imin, int ohour, int omin, int phour, int pmin, int round, double total); int main() { char car; int ihour; int...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

  • i am having issues correcting an error in my program here is my code: #include <iostream>...

    i am having issues correcting an error in my program here is my code: #include <iostream> // define libraries #include <fstream> using namespace std; // Variable definitions: ifstream infp; // file handler enum Tokens {INT_LIT, IDENT, ASSIGN_OP, ADD_OP, SUB_OP, MUL_OP, DIV_OP, LEFT_PAREN, RIGHT_PAREN, LETTER, DIGIT, UNKNOWN,ENDFILE}; Tokens nextToken; // nextToken read from the file. int charClass; // char class char lexeme [100]; // number of characters per line char nextChar; // next char read from the file int lexLen; //...

  • In C++: Please help me correct this code .... All parts with (FIX ME) #include <algorithm> #include <climits&gt...

    In C++: Please help me correct this code .... All parts with (FIX ME) #include <algorithm> #include <climits> #include <iostream> #include <string> // atoi #include <time.h> #include "CSVparser.hpp" using namespace std; //============================================================================ // Global definitions visible to all methods and classes //============================================================================ const unsigned int DEFAULT_SIZE = 179; // forward declarations double strToDouble(string str, char ch); // define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() {...

  • NEED HELP BEING SOLVED IN C++! USE ORIGINAL CODE TO ADD TO AS WELL! #include<iostream> using...

    NEED HELP BEING SOLVED IN C++! USE ORIGINAL CODE TO ADD TO AS WELL! #include<iostream> using namespace std; int main(){    for (int i = 0; i < 7; i++) { int x,y; char opr; cin>>x>>y>>opr;    switch(opr) { case '+': cout<<x<<" + "<<y<<" = "<<x+y; break; case '-': cout<<x<<" - "<<y<<" = "<<x-y; break; case '*': cout<<x<<" * "<<y<<" = "<<x*y; break; case '/': if(y == 0) cout<<x<<" / "<<y<<" = "<<"ERROR"; else cout<<x<<" / "<<y<<" = "<<x/y<<"R"<<x%y; break;...

  • Can you tell me what is wrong and fix this code. Thanks #include <iostream> #include <string>...

    Can you tell me what is wrong and fix this code. Thanks #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; //function void displaymenu1(); int main ( int argc, char** argv ) { string filename; string character; string enter; int menu1=4; char repeat; // = 'Y' / 'N'; string fname; string fName; string lname; string Lname; string number; string Number; string ch; string Displayall; string line; string search; string found;    string document[1000][6];    ifstream infile; char s[1000];...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT