Nathaniel10 34 Junior Poster

This is a follow-up exercise to the one related to reference and dereference operators. Stroustrup asks the reader to modify that program to handle an array overflow. He wants us to specifically use the realloc() function.

I read the tutorial here but didn't understand the example. I read other web pages and found that many recommend not using realloc(), (or malloc()), in favor of new() and resize().

Is this something that I should sweat learning? Are malloc() and realloc() frequently used? Can a person call him/herself a C++ programmer without a thorough understanding of malloc() and realloc()?

Nathaniel10 34 Junior Poster

Thank you, Gerard. You suggestions work perfectly. The code is below.

#include "../../std_lib_facilities.h"

int main ()
{
   char* ch = new char[10];
   char *init_ch = ch;
   char c = ' ';
   cout << "Enter characters separated by a space.\nUse the '!' to indicate the end of your entries." << endl;

   while (cin >> c) {
      if (c == '!') {
         break;
      } else {
	 *ch = c;
	 ch++;
      }
   }

   ch = init_ch;
   for (int i = 0; i < 10; i++) {
      cout << *ch << "  " << &ch + i << endl;
      ch++;
   }

   ch = init_ch;
   delete[] ch;

   keep_window_open();
   return 0;
}

When outputting the addresses of the characters, they increase by 4. So a char is given a size of 4 bytes. I thought a char was 1 byte in C++. Is my IDE (VC++) using 32 bit chars or is that the standard for C++? When I did an exercise on the use of the 'sizeof' operator, it yielded 1 byte for chars and bools.

Am I incrementing the address correctly or not?

Nathaniel10 34 Junior Poster

... if the majority of your search engine marketing budget is being eaten up by "visitors" that spend less than a second on your web page then chances are that your ads are being clicked through by "Internet visitors" deriving from Adsense marketing networks. This practice sucks up your money and generating revenues for the owners of the web pages that your ads appear on. Don't allow the search engine to place your ads on all its "network partners" (as is the default I think).

I also think that is very good advice. I checked the settings on our Adwords account and we were participating in all networks. The non-search network (ads on the pages of websites) had the highest number of impressions, the lowest click-through-rate (CTR), and the highest cost per click. The Google search network had the highest CTR and a much lower CPC. I decided to opt out of the non-search networks.

Nathaniel10 34 Junior Poster

OK. I thought I understood pointers and such but this exercise is revealing that I do not. The task is to read characters into an array created on free store memory (heap), then print them out using the reference and dereference operators.
My code (below) compiles and runs but does not deliver the correct output. The value pointed to is special character like a playing card suit or a brace bracket. The address is the same for all the characters. The variable is not incrementing or it is always pointing to the first element of the array. I need help figuring out what is going on. Here is my code:

#include "../../std_lib_facilities.h"

int main ()
{
	char* ch = new char[10];
	char c = ' ';
	cout << "Enter characters separated by a space.\nUse the '!' to indicate the end of your entries." << endl;

	while (cin >> c) {
        if (c == '!') {
		break;
	} else {
		*ch = c;
		ch++;
		}
	}

	for (int i = 0; i < 10; i++) {
		cout << *ch << "  " << &ch << endl;
		ch++;
	}

	delete[] ch;

	keep_window_open();
        return 0;
}
Nathaniel10 34 Junior Poster

I'm not sure I understand. More generic terms cost more because more people are bidding on them. Highly specific terms are cheaper because fewer people bid on them. You seem to be saying high ranking keywords cost less. I don't think that's it unless I'm missing something.
In other words, I think "shoes" would cost more (to beat out all the bidders) while "brown low top hiking waterproof boot" would cost next to nothing cause who is bidding on something so specific anyway. Yet I think you are saying it's the other way around. "Shoes" would be a cheap high ranking term while the other phrase would be expensive?

That sounds perfectly logical. Ask Google why they are not being logical. Of the keywords I have for my home page 6 or 7 have quality scores of 7 and 8 out of 10. The CPC is dependent on the click-through-rate and the quality score. The relatively high quality score yields a low CPC. The keywords on the other landing pages have quality scores of 3 and 4. This leads to high CPCs. The CPC for my other landing pages is almost 4 times higher than for my homepage.

The means of achieving high quality scores is a separate and extensive topic that I won't address in this post. I only know it is only weakly related to the specificity of the keyword or keyphrase.

Nathaniel10 34 Junior Poster

I would use a while loop as in:

int i = 0;
while (temp < 0.0001) {
   temp = pow(-1,i) * (pow(x,i*2+2)) / (fac(i*2+2));
   cos += temp;
   i++;
}
Nathaniel10 34 Junior Poster

What Guy said is correct on the surface. Underneath is a different story. I have an ad campaign for the homepage of the small site I manage and ads for 5 other landing pages. The landing pages are more specific than the homepage, as Guy advises.

The problem is that the keywords for the homepage rank higher than those for the other landing pages, making its costs per click (CPC) much lower than those of the landing pages. It is much more cost effective to bring traffic to the homepage, despite a possibly lower buying rate. The landing pages have low ranked keywords so they don't attract traffic, buying or non-buying. The better tactic, which I try to do, is to use the homepage to direct traffic to the other more specific landing pages.

Nathaniel10 34 Junior Poster

This last program looks pretty good. You have a logic error that stems from your decision to use this intermediary variable you call 'distance'. You should realize that 'distance' and radius' are the same thing in your program because the distance you are calculating on line 75, from the circle center to its edge, IS the radius.

1) I would rename the CalculateDistance() function as CalculateRadius() and delete what you currently have as CalculateRadiius().

2) The diameter of your circle, on line 48, needs to be the 'distance' (now 'radius') times 2.

3) Because you are using variables 'radius', 'circumference', and 'area' in your cout statements, your functions need to return those variables. So the function for the radius should be

float CalculateRadius(float x1, x2, y1, y2)  {
   radius = sqrt[(x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)];
   return radius;
}

Are you running these versions of your program? I can't see you getting the correct output from your last program if you had run it.

EDIT: You have placed the functions BELOW the lines in which you use their return values. I am not sure on this point, but I suspect that the value of a variable, say radius, needs to be determined BEFORE you use it in an equation or cout command. In your variable declaration lines, you haven't initialized them to any particular values such as 0.0. So line 48 should yield an error because you are trying to …

Nathaniel10 34 Junior Poster

It looks mostly fine to me. I am still learning C++ but based on the complexity of your program, I think I am slightly more advance than you right now.

Does your code compile and run, giving the correct result? I am suspicious about your

cin

statements on lines 16 and 18. I have not seen any used with parentheses the way you have done. Still, your math is solid.

For more elegance, I would set up radius, circumference, and area as functions to call in the main section.

Nathaniel10 34 Junior Poster

Correction! I misread the available memory on my computer. Mike 2000 is correct that it should have been 467 M. The display read 466,800 but I forgot that display was in K's so I should have added another 3 0's to the display number.

This has been a very informative exercise for me. Many thanks to those who contributed. I feel now I can almost call myself a geek! I am declaring the thread solved.

Nathaniel10 34 Junior Poster

@csurfer,

A question in Stroupstrup's book, that I was not considering trying, is: Which way does the stack grow? Which way does the free store (heap) grow? Write a program to that answers those questions.

What you just said about stack and heap growing from opposite ends suggests that this issue might be pretty important. If one type of memory has increasing address values and another has decreasing address values, then the way pointers are used should depend on the type of memory. By that I mean, if we want to move a pointer along an array, or across several arrays, then we should use the increment operator (++) for one type of memory and the decrement operator (--)for the other type.

Does that make sense? Would a program to show this involve creating a series of variables, then printing each sequential variable and its address? That should show whether the next variable is put into a higher address or lower address than the previous variable.

Nathaniel10 34 Junior Poster

So I tried to exhaust the memory on my computer. I use a laptop running XP that has 1 G of RAM. I used CTRL+ALT+DEL / Performance to see how much available memory there was. Before running the program there was 467K of available memory. I eventually ran the following program.

int main ()
{
	for (int i = 0; i < 150000; ++i) {
		double* pi = new double[2000];
		*pi = i * 2.5;
		cout << i << "  " << *pi << endl;
	}

	keep_window_open();
    return 0;
}

It stopped at iteration 133,033. My computer was almost non-responsive. After a few minutes, VC++ gave the following error message:
"Unhandled exception. std::bad_alloc at memory location (hex address)."
Is that was is supposed to happen? Is this what usually happens?
Thanks for your help.

Nathaniel10 34 Junior Poster

An exercise in Stroupstrup's book is to write a program involving memory allocation with an infinite loop and let it run until it crashes. He says the crash will be due to memory exhaustion. He also suggests researching the topic.

I did and am frightened by what I found. The vast majority of the pages I read were related to hacker attacks. Apparently, memory exhaustion/stack overflow can be used as a form of denial of service attack. Many of these said that Chrome is vulnerable to this attack. (from 2008/2009) Only a handful dealt with non-attack memory exhaustion and discussed a solution. ini_set('memory_limit',-1).

What is Stroupstrup trying to get at with this exercise? What will happen if I run a program with an infinite loop? I am very reluctant to run such a program because I am fearful of doing something I can't undo. How does a programmer estimate the amount of memory that a program might need in order to avoid this situation? For example, the number of int variables times 4 bytes per int?

Nathaniel10 34 Junior Poster

I took your suggestion and used a pointer array. The program ran and yielded the desired results. I just don't think my program was what Stroustrup was intending for us to write. The code is below. Constructive comments are very welcome.

#include "../../std_lib_facilities.h"

int main ()
{
	int p0[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	int* p1[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

	int q0[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	int* q1[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

	for (int i = 0; i < 10; ++i) {
		p0[i] = 2 * (i + 1);
		p1[i] = &p0[i];
	}

	for (int i = 0; i < 10; ++i) {
		cout <<"Array place " << i << " has value " << p0[i] << ".\n";
	}
	cout << "  \n";
	for (int i = 0; i < 10; ++i) {
		cout <<"Array place " << i << " has value " << q0[i] << ".\n";
	}

	cout << "  \n";
	cout << "  \n";

	for (int i = 0; i < 10; ++i) {
		q1[i] = p1[i];
     	        q0[i] = *q1[i];
	}

	for (int i = 0; i < 10; ++i) {
		cout <<"Array place " << i << " has value " << q0[i] << ".\n";
	}

	keep_window_open();
        return 0;
}
Nathaniel10 34 Junior Poster

Thank you, guys. I tried

int* p1 = &p0[0];

and it worked fine. Another poster explained to me that I had defined an array in line 3 (p0[7]) but set a pointer to an int in line 4 (&p0). I had to add the subscript to turm p0 back into an array.

Nathaniel10 34 Junior Poster

I am trying to do an exercise in Stroustrup's book. The task is to create two arrays (with different values) and pointers to each array, and copy the first array to the second using the pointer and reference operators. My code is below.

#include "../../std_lib_facilities.h"

int main ()
{
	int p0[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	int* p1 = &p0[0];

	int q0[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	int* q1 = &q0[0];

	for (int i = 0; i < 10; ++i) {
		p0[i] = 2 * (i + 1);
	}

	for (int i = 0; i < 10; ++i) {
		cout <<"Array place " << i << " has value " << p0[i] << ".\n";
	}
	cout << "  \n";
	for (int i = 0; i < 10; ++i) {
		cout <<"Array place " << i << " has value " << q0[i] << ".\n";
	}

	cout << "  \n";
	cout << "  \n";

	q1 = p1;
	q0[0] = *q1;

	for (int i = 0; i < 10; ++i) {
		cout <<"Array place " << i << " has value " << q0[i] << ".\n";
	}

	keep_window_open();
        return 0;
}

The program compiles and runs. BUT the output is correct only for q[0], the first element of the second array. The values of the other array elements remain unchanged. I don't know if I think I am supposed to do is even possible. I thought the rest of the array would copy automatically after pointing to the first element (line 27). Thanks in advance for your help.

Nathaniel10 34 Junior Poster

I am trying to do an exercise from Stroustup's book. The task is to create an array of 7 ints, assign its address to another variable, then print out the array value and the address. My code is below.

int main ()
{
	int p0[7] = {0, 0, 0, 0, 0, 0, 0};
	int* p1 = &p0;


	for (int i = 0; i < 7; ++i) {
		p0[i] = 2 * (i + 1);
	}

	for (int i = 0; i < 10; ++i) {
		cout <<"Array place " << i << " has value " << p0[i] << ", and its address is " << p1 << ".\n";
	}

        keep_window_open();
        return 0;
}

My problem is that I get a compile error on line 4 saying that "a value of type int(*)[7] cannot be used to initialize an entity of type int*". I don't understand that message nor how to correct the problem. Thanks in advance for your help.

Nathaniel10 34 Junior Poster

I would like to place a caret (^) above certain characters in my text. The text decoration options I find are underline, overline, and strike-through. I also find ASCII characters with carets but theses are only vowels, and I would like any character to have a caret.

Is it possible to place a caret above characters? Is there a way to do 'over-strikes' in HTML like one can do in Word or WordPerfect? Thanks.

Nathaniel10 34 Junior Poster

I have this arrangement on the site I manage. I agree with fobos that the best strategy is to have your visitors sign up for free content and then separately pay for non-free content.

Unless you have expertise in SSL and credit verification, I STRONGLY suggest you use a payment gateway. Payment gateways have the option of a site (you) sending their customers to the gateway's secure site, entering their credit and payment information there, and then returning to your site after payment is confirmed or denied.

Chrishea is correct that you will need a separate database or separate field for storing the payment information. I have one database for storing information on registered users and another database for storing information on the content for which users have paid. The second database may sound like double work. But the conventional wisdom on databases that I read says to keep each database focused on one theme, then link all the databases through a common field (such as user_id). Don't make one database containing all the fields in the world.

I do have a rather elaborate cookie mechanism that checks that a user has the right to the content he/she is trying to access. I have a different cookie value for each section of content. The user must return to his/her user home page, where they see the content sections to which they have rights and select which they wish to access, in order to move from one section …

Nathaniel10 34 Junior Poster

I had a similar problem which I think I posted here. The recommended solution, which worked, was to use a cin.clear() statement to empty the input buffer so cin >> can be used again. Why is cin.ignore the solution for this problem? Does cin.ignore also empty the input buffer?

Nathaniel10 34 Junior Poster

I have AdSense on a small website I manage. I don't understand the large variance in the revenue per click that I am experiencing. I can earn $10 on a total of 10 clicks one day, and yet earn only $5 on a total of 25 clicks another day. I suspect this is due to the cost-per-click that advertisers decide upon in their AdWords accounts, but I am not sure. Does anyone know for sure? Thanks.

Nathaniel10 34 Junior Poster

I am reading the first chapter on graphics in the Stroustrup book. He explains that we students will need to download the files of a GUI toolkit in order to run programs containing graphics. He recommends the "Fast Light Tool Kit, FLTK" because the book's programs are based on that tool kit.

I would like some guidance as to the variety of GUI toolkits that are available and how they compare to each other. Which are compatible with VC++ Express? Which are most suitable for a beginner to C++? Which are free? Thanks in advance.

Nathaniel10 34 Junior Poster

Thanks for the explanation. I was interpreting the logs as accessed pages rather than requested pages.

Nathaniel10 34 Junior Poster

Thanks for the explanation. It cleared things up for me.

Nathaniel10 34 Junior Poster

No. The escape lines were prior to the DB connect line. Thank you very much for the essential piece of information.

Nathaniel10 34 Junior Poster

OK! I added the lines

cin.clear();
while (cin.get() != '\n');

and the program ran correctly. But only after correcting another error on line 35: "cout" should have been "ost".

Thank you very much for your help in this exercise. I am onto the next one!

Nathaniel10 34 Junior Poster

I hope this is the correct forum for this question. I manage a small website. The site uses a database with MySql. When I launched the site, around 3 years ago, the PHP code I wrote had minimal security and validation in PHP because I relied on javascript validation for the forms involved. Over the 3 years, I learned about the risks of injection attacks and other potential site disruptions via forms and database commands. I found recommendations for using the

myslq_real_escape_string()

to improve security. This past week I decided to implement this security measure by escaping the strings that were added to the database.

My site stopped functioning correctly. It only returned to normal after I removed ALL the escape string codes. My question is: why did this happen?

I escaped the username and password for login, and then the login process generated errors. It would yield a user already logged in error, a user unknown error, and an incorrect password error. I escaped the registration strings and the registration process and generated the error that the requested username was already taken by another user. When I checked the database itself, there were fields that were empty despite being filled in the form.

I thought I understood what the

myslq_real_escape_string()

did. I do not, or at least not well enough. Can someone explain to me what EXACTLY this function does?

Nathaniel10 34 Junior Poster

I manage a small website. I went over the logs this morning and found a page reference on the site that should not have been there. It was of the format "/xmlrpc.php". I did a search for the term and found the XMLRPC website.

I didn't understand what was written on the website. It seems to be some new data transfer protocol that enhances the functioning of sites written in PHP. My site is written in PHP but I don't understand how this file could be added to my site without my permission.

Can anyone explain to me what this is all about? Thanks in advance.

Nathaniel10 34 Junior Poster

I manage a small website. I went over the logs this morning and found a number of pages or page references on the site that should not have been there. Most were of the format
"/_vti_bin/". I did a search for the term and learned about the Front Page debacle.

I couldn't get a good idea of how these files got there or what damage they could do. What little I did understand was that a visitor to my site had an infected machine that tried to upload or access Front Page directories. Apparently, FP has MANY weaknesses that allow hackers to take over sites that were made using that software. Most of the info I read said that if FP was not used to write and upload the site files, and if the site is NOT on a Windows server (mine is on a Linux server.) then there was little to worry about.

Can anyone add to or correct this information? What are the risks regarding these VTI files? Despite the fact that they are listed in the logs of visited pages, I can't find them in the site's directories to delete them. This is very new to me and I need help with it. Thanks in advance.

BTW: I should add that I noticed these files only in the past 7 - 10 days.

Nathaniel10 34 Junior Poster

@mit,

Yes. I did use Ctrl+Z to exit the

while (cin >> x >> y);

loop. If I had used an exit condition like

if (x == -999 && y == -999) break;

would I still have had the problem with

cin >> oname

?


@first,

I will add the

cin.clear()

and

cin.get()

lines and get back to you this evening. I copied the example from my textbook and it did not mention

cin.clear()

or discuss the need to empty or reset the cin function before using it again.

Stroustrup does that a lot. He uses examples and has exercises that require knowledge not yet discussed. This business of finding landmines by walking on them is a frustrating way to learn.

BTW Will this also apply to the file input section,

cin >> iname

?

Nathaniel10 34 Junior Poster

@firstPerson,

1) The program crashes just after line 29. So say line 30.

2) The last output to the screen is the prompt to enter the name of the output file. That is line 29. Then a MS alter window pops up with the message of an unhandled exception. Even though the cursor still blinks in the IDE screen and the window is active, it does not accept any input from my keyboard.

3) The data to be written to the output file is a number of coordinates. I have been using 3 points, so the file would have 3 pairs of integers representing (x,y) coordinates, one pair per line. N.B. The output file doesn't exist because I was not able to open it.

Nathaniel10 34 Junior Poster

I am doing an exercise from Stroustrup's book. It is the drill from chapter 10 on input and output streams. The program I wrote compiles but crashes when it reaches the prompt for the output file name. My IDE (VC++ Express) simply says there is an unhandled exception yielding a runtime_error at a memory location. Clearly there is a problem with opening the output file stream but I have no idea what it could be. Help is very much appreciated.

#include "../../std_lib_facilities.h"
       
struct Point {
	    int x;
	    int y;

	    Point(int x_axis, int y_axis) : x(x_axis), y(y_axis) {}
};

int main ()
{
	vector<Point> original_points;
	vector<Point> processed_points;
	int x = 0;
	int y = 0;
	string oname = " ";
	string iname = " ";
     
	cout << "Please enter the coordinates for each point.\n";

	while (cin >> x >> y) {
		original_points.push_back(Point(x,y));
	}

	for (int i = 0; i < original_points.size(); i++) {
		cout << "(" << original_points[i].x << ", "<< original_points[i].y << ")" << endl;
	}

	cout << "Please enter the output file name.\n";
	cin >> oname;
	ofstream ost(oname.c_str());
	if (!ost) error("output file can't be opened");

	for (int i = 0; i < original_points.size(); i++) {
	    cout << original_points[i].x <<" " << original_points[i].y << endl;
	}

	cout << "Please enter the input file name.\n";
	cin >> iname;
	ifstream ist(iname.c_str());
	if (!ist) error("input file can't be opened");

	while (ist >> x >> y) {
		processed_points.push_back(Point(x,y));
	}

	for (int i = 0; i < processed_points.size(); i++) {
	    cout << "(" << …
Nathaniel10 34 Junior Poster

I am new to C++ and am still learning it. In college decades ago, I took Cal III and learned about the Maclaurin and Taylor series expansions. A couple of years ago I dusted off my old textbook and wrote a Javascript program that computes normal probability values using the Taylor series expansion. I understand how to write your program.

The issue is whether YOU understand the problem to be solved. Before I could write the normal probability program, I had to compute the normal probabilities BY HAND! I wrote pseudocode to organize the different parts of the program. (One part, for example, is the factorial function.) I drew a flowchart to track the movements of values, specifically, the function calls and function returns. (For example, the call of the factorial function and the return of the factorial function value.)

If you are able to answer the problem's questions by hand, then you can (eventually) write a C++ program to solve the problem. People on this site will be able to help you with the code. If you can't, then no one can help you. Others will be able to solve the problem for you, but you yourself still won't be able to solve it. You would need to go back to calculus and improve your understanding of infinite series.

Why don't you share some pseudocode or anything else you have done to organize your thoughts and ideas about this problem?

Nathaniel10 34 Junior Poster

I had to do this very exercise last month. However, the solution looked nothing like what you have.

The values of the set were input into a vector using the push_back() function. Then the stated statistics were found using the sum() function and loops.

However, Vernon is absolutely correct. If you don't understand statistics (mean, variance, etc.), then you can't write a program to compute them. The author of the book I am using has that as the very first rule: You can't program what you don't understand. First, understand the problem.

Nathaniel10 34 Junior Poster

I am just learning C++ and will have to write the same exercise when I get to the chapter on graphics. I wrote similar non-graphics programs when I was learning BASIC years (decades rather) ago.

I follow and understand what FirstPerson wrote much more than what the OP wrote.

I can't tell if the angles the OP has are measured in radians or degrees. He quotes 80 in his question so that must be degrees. Does C++ let you choose which?

I can't find a passage of time in the OP's code. Is it 'glutTimerFunc'? FP has time passing at a rate of 1 second per iteration (dt = 1).

The OP says that the target is a moving ship. I can't find any code that seems to relate to the position of the ship or whether the ship is hit or not. Does 'Raster' refer to the ship?

I hope there are more comments because I would like to learn how to graphically represent this type of problem.

Nathaniel10 34 Junior Poster

I am just learning C++, but knew other programming languages beforehand. I am finding that prior knowledge invaluable.

If you are new to programming of any type, then I suggest you start with some simple languages to learn programing concepts. Definitions of variables, loops, code formatting are important. Spend a month or so playing around with BASIC or Scratch.

Then learn a language that is object oriented. Object Oriented Programming (OOP) is the standard. I learned javascript I did before C++ and found it was extremely helpful in understanding data structures.

The classes in C++ are difficult enough (IMHO) without adding the stuff it has in common with other languages on top of that.

As Vernon said, programming is a big field. There are different languages because each satisfies a different need. I took up C++ because I want to write some programs that have gaming features, C++ is the language used to write games.

Nathaniel10 34 Junior Poster

Why have you marked this thread as solved if your program doesn't yet run correctly? I ran a version of your program and it worked for most values of deposits.

int main()
{
double deposit1 = 0;
double deposit2 = 0;
double simple = 10;               // The two methods must have a difference large 
double compound = 0;              // enough to exceed the loop condition.
double interest1 = 0.10;
double interest2 = 0.05;
double years = 1;

cout << "Enter your deposit for first choice."<< endl;
cin >> deposit1;
cout<< "Enter your deposit for the second choice."<< endl;
cin >> deposit2;

while (abs(simple - compound) < 5.00) {
   simple = deposit1 + deposit1 * interest1 * years;
   compound = deposit2 * pow((1.00 + interest2), years);
   ++years;
}
cout <<"The simple amount is " << simple <<".\n";
cout <<"The compound amount is " << compound <<".\n";
cout <<"The time period is " <<years <<" years.\n";

keep_window_open();
return 0;
}

Because of the interest rates you have chosen, deposit2 should be larger than deposit1. Otherwise, the compound method might not catch up to the simple method quickly enough and the loop may end up infinite.

Nathaniel10 34 Junior Poster

@fbody,

You have a point. Perhaps the OP can give an example of a lab he is having difficulty starting and we can help him write pseudo code for it?

Nathaniel10 34 Junior Poster

Thinking about this more, I would not have the sums at all.

while ((simple - compound) < 1.00) {
   simple = deposit1 + deposit1 * interest1/100 * years;
   compound = deposit2 * pow(1.00 + interest2/100, years);
   years++;
}
Nathaniel10 34 Junior Poster

WOW! Not be too harsh, but doesn't your professor/college teach about pseudo code?
I am just learning C++, but my textbook stresses that the most important part of programming is organizing your thoughts and ideas. This is done by writing pseudo code and a grammar BEFORE writing the program code itself. Put the horse before the cart.

Ancient Dragon commented: good point :) +33
Nathaniel10 34 Junior Poster

I am still just learning C++ so my observations may not be the best. It seems to me that you are using the wrong type for your variables. You are using integers. But when you divide the interest rate by 100 yo get a decimal that is less than one, NOT an integer. You need to change the type to float. In addition, your loop is probably infinite because you will never get an exact equality. The better exit condition is (simple investment - compound investment) < precision amount.

My field is business and I know finance. You are calculating the 'sums' incorrectly. The compound investment is: future balance = (original balance + interest rate) raised to the power of number of years. The simple investment is: future balance = original balance + (original investment * interest rate) * number of years.

N.B. In line 12, you haven't divided interest2 by 100 to make it a rate. As Vidit noted, you are not incrementing by the year.

Nathaniel10 34 Junior Poster

@firstperson,

Thank you for your suggestions. They were a little advanced for me. I realize I need to review the chapter on error and exception handling. The chapter I am reading only touches on structs, so I need to research that topic more deeply.

Nathaniel10 34 Junior Poster

Me Again! This program is for exercise 5) of chapter 9 in Stroustrup's book.
It was a challenge for me. I gave up on trying to use

getline()

because it required substantial parsing of the line before I could use the input. I will add it when I am more proficient in that tool. I thank another poster again for his/her suggestions about the Book constructor. So here is the code. It is fairly long compared to most other examples I have seen here. Is that unusual? I snipped code to make it faster to read and follow.

/*
This program solves an exercise related to a writing software program for a library. The first requirement is to create a class 
holding vectors of book characteristics; ISBN, title, author, copyright date, and an indicator of whether a book is checked 
out.  The class should also hold functions that return a book characteristic when queried. Additional functions should 
perform input validation.
*/
      
#include "../../std_lib_facilities.h"
       
class TitleExcept: public exception    // Class for handling errors about the book's title.
{
virtual const char* what() const throw()
{
return "Please enter the book's title using only letters.\n";
}
} errortitle;

SNIP

class Book {
      private:
            vector<string>ISBNs;
            vector<string>Titles;
            vector<string>Authors;
            vector<int>CR_Dates;
            vector<char>Checked_In;

     public:
     Book()
  	  :Titles(3),
	   Authors(3),
	   CR_Dates(3),
	   ISBNs(3),
	   Checked_In(3)

	   {
	   Titles[0] = "CatintheHat";
	   Titles[1] = "CharlottesWeb";
           Titles[2] = "NineteenEightyfour";

	   Authors[0] = "DrSeuss";
	   Authors[1] = "EBWhite";
           Authors[2] = "GeorgeOrwell";

	   CR_Dates[0] = 1957;
	   CR_Dates[1] = 1952;
           CR_Dates[2] = 1949;

     	   ISBNs[0] = "0-2-6-8";
	   ISBNs[1] = "1-8-3-r"; …
Nathaniel10 34 Junior Poster

@mike,

Thank you very, much for your detailed comments. I carefully compared your code to mine and I think I understand what you called my mistake.

One mistake that is very important here is that you don't need to pass the vectors Names and Ages to all the functions you have. Since Sort and Print are member functions (called methods) they have access to the data inside the object of type Name_Age, so they can access the vectors Names and Ages directly without having to pass them as parameters.

When I called the sort function in line 44, I included arguments Names and Ages. Therefore, when I defined it in line 47, I needed to include those arguments in its definition. Hence the error message when my argument was a string rather than a vector string.

However, if I had not included an arguments when I called Sort or Print, the way I had when I called Read_ages in line 29, then I would not have needed to include any arguments when I defined those functions, as I did not have to do when I defined Read_ages in line 37. I don't remember why I decided to do that. But now I know and understand better.

Nathaniel10 34 Junior Poster

I did exercise 2) of chapter 9 in Stroustrup's book. That chapter is about classes, its members, enumerations, constructors, etc. This is my first attempt at writing a program with classes containing public and private members that are both data variables and functions. It compiled and ran correctly,BUT.

The exercise was a continuation of another exercise in an earlier chapter. That exercise only required writing functions, no classes. I thought I could cut and paste that program into this one and just adapt the class. I couldn't and that's where I need feedback. I was getting many compile errors saying that the subscript needed to be used with an array type. My IDE (MS VC++ Express) underlines errors and gives hints as to the solution. The solution was to write

vector<string>name;
function(vector<string>name);

instead of

vector<string>name;
function(string name);

In other words, my program seems to work correctly but I don't understand why.
This is the program.

/*
This program solves an exercise.  The requirement is to first create a class holding a vector of names of individuals and a vector 
of their ages as members.  Then write a function that reads the names into the vector, a function that reads their ages into the 
vector, a function that sorts the names alphabetically and also sorts the ages to remain matched to the names, and finally a 
function that prints out the sorted names and ages.  These functions should be members of the class.
*/

#include "../../std_lib_facilities.h" …
Nathaniel10 34 Junior Poster

WOW! You guys are pretty patient and generous with this poster who shouts at someone who offers him help rather than thanks that person.

Nathaniel10 34 Junior Poster

Thanks for the suggestions. I took a look at Boost.org. Right now most of their stuff is beyond my understanding. But I am glad I know it exists!

Thank you for the heads-up on srand(). I now see the difference in calling it each time the function is called, as I have it now, and each time the program is run.

@dusk,
I am now reading chapter 9 of Stroustrup's book which covers classes, members, constructors, enumerations, etc. I like your suggestion for RNG, it fits in perfectly with what Stroustrup teaches.

@first,
You are right about RAND_MAX. I wrote it the way I did to avoid problems. I tried to write that line with everything as in

b = lower + (rand() / RAND_MAX) * (upper - lower);

It compiled and ran but the output was zeros for all the generated random numbers. After I separated the rand functions/variables from that line, it yielded the correct output. I am much more hyped about getting a program to run correctly than elegantly. When I get good and can write correctly running programs with ease, I will pay more attention to elegance, maintenance, and that stuff.

Nathaniel10 34 Junior Poster

An exercise is to write a program that generates random numbers within user specified limits. The program I wrote is as follows and it runs correctly.

#include "../../std_lib_facilities.h"

void randnum(double lower, double upper, int n)  // Generate 'n' random numbers uniformly distributed 
{	                                         // between lower and upper limits.
	double a = 0;
	double b = 0;

	srand((unsigned)time(0));

	for (int i = 1; i < n+1; ++i) {
		a = rand();
		b = lower + (a / 32767) * (upper - lower);   // RAND_MAX for MS VC++ Express is 32,767.
		cout << i <<"  " << b <<endl;
	}
}

int main () 
{
    int z = 0;
    double l = 0;
    double u = 0;

    cout <<"Enter the lower and upper limits for, and the number of random numbers \nto be generated, separated by a space.\n";
    cin >> l >> u >> z;

    randnum(l,u,z);

    keep_window_open();
    return 0;
}

It occurred to me that this only generates numbers uniformly over the range. I have used random number generators that use different probability distributions to generate the numbers. There is uniform, normal, Poisson, binomial, etc. I looked for probability distributions in C++, but found more questions than answers, The math.h header doesn't seem to support any probability functions.

If I want to generate numbers that follow the normal distribution, do I first have to write a function that estimates the normal probability density myself?
(I have done that in Javascript so I think I can do it in …

Nathaniel10 34 Junior Poster

You guys were right, thank you. I was not using the correct form of the swap function. I should have used

swap(first,second);

When I did, the program compiled and ran correctly. Here is the code.

#include "../../std_lib_facilities.h"

void reverse(vector<int>v)
{
	for (int i = 0; i < v.size()/2; ++i) {
           swap(v[i], v[v.size()-1-i]);
	}

	for (int i = 0; i < v.size(); ++i) {
	   cout << i <<"  " << v[i] << endl;
	}
}

int main () 
{
	vector<int>cs;
	int c = 0;
    
	while (cin >> c) {
		if (c == -999) {
		    reverse(cs);
		    break;
		} else {
		cs.push_back(c);
		}
	}
	
    keep_window_open();
    return 0;
}
Nathaniel10 34 Junior Poster

This is an exercise in chapter 4 of Stroustrup's book on programming in C++.

You enter the digits into an vector using the push_back operator.
Use the sort(vector.begin, vector.end) to rank the digits from lowest to highest.
vector[0] = lowest digit, vector[vector.size()-1] = highest digit, vector[(vector.size()-1)/2] = median digit assuming an odd number of digits, then sum the vector elements and divide by vector.size() to find the mean.