When Even The Posted Solution Isn't Working

  • Thread starter Thread starter Heisenberg.
  • Start date Start date
  • Tags Tags
    even
Click For Summary

Discussion Overview

The discussion revolves around troubleshooting a C++ programming exercise from the book "Programming: Principles and Practice Using C++" by Bjarne Stroustrup. Participants are addressing errors encountered in the provided code, exploring potential fixes, and discussing the implications of the book's instructions.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant describes their attempt to implement a code example from a C++ textbook, encountering errors despite following the provided solution.
  • Another participant identifies several syntax errors in the original code, including undefined functions and misplaced operators.
  • A later reply provides a corrected version of the code, introducing an error handling function and suggesting changes to the exception handling mechanism.
  • One participant expresses confusion regarding the introduction of concepts not yet covered in their studies, specifically the use of exceptions.
  • Another participant suggests that the immediate closing of the console window after execution is normal behavior and offers solutions to prevent it.
  • There is a discussion about the nature of examples in Stroustrup's books, with some participants noting that they may not always be fully functional or intended to be compiled directly.

Areas of Agreement / Disagreement

Participants generally agree on the presence of errors in the original code and the need for corrections. However, there is no consensus on the appropriateness of the book's exercises or the clarity of its instructions.

Contextual Notes

Some participants note that certain functions and error handling mechanisms introduced in the discussion may not have been covered in the chapter being referenced, leading to confusion.

Who May Find This Useful

Readers interested in C++ programming, particularly those working through exercises in Stroustrup's textbooks, may find this discussion relevant for understanding common pitfalls and troubleshooting strategies.

Heisenberg.
Messages
68
Reaction score
0
So I have been teaching myself some c++, and as I tried to do an example my guide book showed me: that is where things went awry. The book I have been using is Programming:Principles and Practice Using C++ By Bjarne Stroustrup. I used the solution for the example where I got stuck on a certain part - I did not understand exactly what the book was doing at that part, but threw it in anyway. Even with the solution as a guide, my code still seems to produce errors. Here is the code:

//Write a program that prompts the user to enter two integer values.
//Store these values in int variables named val1 and val2. Write your program to determine the smallest,
//largest, sum, difference, product, and ratio of these values and report them to the user.

#include <iostream>
#include <conio.h>

using namespace std;

int main ()

{
int val1=0;
int val2=0;
count <<"Please enter two integer values separated by a space: ";
cin >> val1 >> val2;

if (!cin) error ("something went bad with the read");
count << "values : "<< val1 << "," << val2 << "\n";

if (val1 < val2) << val1 << "is smallest. \n";
if (val2 < val1) << val2 << "is smallest. \n";
if (val1==val2) count << val1 << "and" << val2 << "is equal.\n";

count << "sum" << val1+val2 << "\n";
count << "product : " << val1*val2 << "\n";
if (val2==0)
count << "good try! but I don't divide by zero!\n";
else
count << "ratio (val1/val2): " << val1/val2 << "\n";

if (val1<0) count << val1 << "is negative\n";
count << "difference (val1-val2) :" << val1-val2 << "\n";
if (val2 !=0) count << "remainder (val1%val2):" << val1%val2 << "\n";
count << "square(val1) : " <<val1 * val1 << "\n";

}
catch (runtime_error e) {
count << e.what () << "\n";

getch ();
return 0;
}

The first error is this if (!cin) error ( "something went bad with the read"); - this is what the solutions say, I haven't seen this before and am not sure how to go about fixing this program.

Thank-You in advance!
 
Technology news on Phys.org
Ok, I actually took your code and compiled it, and here is what I got:

error C3861: 'error': identifier not found
error C2143: syntax error : missing ';' before '<<'
warning C4390: ';' : empty controlled statement found; is this the intent?
error C2143: syntax error : missing ';' before '<<'
warning C4390: ';' : empty controlled statement found; is this the intent?
error C2059: syntax error : 'catch'
error C2143: syntax error : missing ';' before '{'
error C2447: '{' : missing function header (old-style formal list?)

Did you really copy this from the book ?
If so, maybe they made mistakes for you to find them, as an exercise ?
If not, here are the mistakes:

- if (!cin) error ("something went bad with the read");
error doesn't seem to be defined, check in what .h it should be declared

- if (val1 < val2) << val1 << "is smallest. \n";
Something is missing here. Didn't you forget a count ?

- if (val2 < val1) << val2 << "is smallest. \n";
Same here.

- catch (runtime_error e) {
Where is the try ? And why is the catch outside of the main function ?

All the other errors you get come from these.
 
Last edited:
And here is the fixed version of your code.

Code:
#include <iostream>
#include <conio.h>

using namespace std;

void error(const char* str)
{
    cout << str;
    exit(0);
}

int main ()

{ 
    try
    {
    int val1=0;
    int val2=0;

    cout <<"Please enter two integer values separated by a space: ";
    cin >> val1 >> val2;

    if (!cin) error("something went bad with the read");
    cout << "values : "<< val1 << "," << val2 << "\n";

    if (val1 < val2) cout << val1 << "is smallest. \n";
    if (val2 < val1) cout << val2 << "is smallest. \n";
    if (val1==val2) cout << val1 << "and" << val2 << "is equal.\n";

    cout << "sum" << val1+val2 << "\n";
    cout << "product : " << val1*val2 << "\n";
    if (val2==0)
        cout << "good try! but I don't divide by zero!\n";
    else
        cout << "ratio (val1/val2): " << val1/val2 << "\n";

    if (val1<0) cout << val1 << "is negative\n";
    cout << "difference (val1-val2) :" << val1-val2 << "\n";
    if (val2 !=0) cout << "remainder (val1%val2):" << val1%val2 << "\n";
    cout << "square(val1) : " <<val1 * val1 << "\n";

    }

    catch (runtime_error e) {
        cout << e.what () << "\n";

        getch ();
        return 0;
    }

}

Note that I added the error function. I'm not quite sure about what your book meant as I don't remember if 'error' is part of the standard C++ library (I don't use it much ;))
 
Ah thank you for your help! This book is quite the nuisance - there is no explicit indication that I supposed to find any errors - for the exercise was merely create so and so of a program - after trying to compile your code these are the current errors:

ex4 cap 3.cpp: In function `int main()':
ex4 cap 3.cpp:44: error: `runtime_error' has not been declared
ex4 cap 3.cpp:44: error: invalid catch parameter
ex4 cap 3.cpp:45: error: `e' undeclared (first use this function)
ex4 cap 3.cpp:45: error: (Each undeclared identifier is reported only once for each function it appears in.)
make.exe: *** ["ex4 cap 3.o"] Error 1
Execution terminated

I also do not know what's the deal with the error function - mind you this ex was in chapter 3 of the book, so I am surprised some higher level coding was introduced since it was not covered in the chapter. I am not sure why there is a main int error - I usually get those if I have more than one file in a same project and explicitly defined int main1 or main2 etc. but this is the only file in this project . The last three errors are things I have no idea of for I was not introduced to them yet. So I wouldn't know how fix them without some prodding in the right direction. Any ideas?
 
Ok hmm. It might depend on your compiler. Which one are you using ?

A quick fix would be to replace:

Code:
    catch (runtime_error e) {
        cout << e.what () << "\n";

        getch ();
        return 0;
    }

by

Code:
    catch (exception& e) {
        cout << e.what () << "\n";

        getch ();
        return 0;
    }
 
im using bloodshed dev version 4.9.9.2 - and the program did run successfully! thanks for that! - but upon trying to test it: i submitted two integer values and the result window closes immediately after - I am not sure where in my code where that would enable the program to do that - or what errors or flawed syntax in code would do that as well.
 
Ok glad to know that it worked.
If the window closes right away, don't worry you've done nothing wrong !
Actually, when you enter the two ints, the program keeps going and then comes to an end.
When it ends, the console window closes (it's the normal behavior).

You have two solutions then. Either configure the console window not to close, or do
a little workaround by adding a getch() at the end of the program. It will then pause
until you press a key before closing.
 
I don't know this particular book, but as far as I remember from Stroustrup's "C++ Programming Language" examples he gives are not necessarily correct programs intended to be compiled as shown. They sometimes use some functions that are not defined, but it is clear what they should do - like, say "display_error_message()". I think this is called top-down approach - you first define the general framework, later you write code that executes tasks as assigned. Could be book you have mentioned is different.
 
well I agree with you, and a lot of the chapter's and example questions are formatted in that way - except this was in the exercises section and he explicitly states in the solutions:
// note that different compilers/SDEs keep header files in different places
// so that you may have to use "../std_lib_facilities.h" or "../../std_lib_facilities.h"
// the ../ notation means "look one directly/folder up from the current directory/folder"

so now I'm thinking perhaps I should get more libraries, I mean he likes to use std_lib_facilities.h in his solutions - I have been using iostream, but they have always worked before.

*also in this case there was just an example - usually he'll post a code and he would state that there would be errors or we would have enter certain functions - there was no indication for a top down approach in this section of the chapter :/
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 39 ·
2
Replies
39
Views
5K
Replies
12
Views
2K
Replies
10
Views
2K
  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 35 ·
2
Replies
35
Views
4K
  • · Replies 66 ·
3
Replies
66
Views
6K
Replies
5
Views
2K
  • · Replies 75 ·
3
Replies
75
Views
7K