• 0

[C++] My Book's examples are not working


Question

Hello again everyone.

I am making this post not because I am not understanding a specific coding error this time, but rather because the examples of code in my book don't work.

The book I am trying to teach myself C++ from is "C++ Without Fear" by Brian Overland.

I've reached a point in my book where I've started doing some work with creating external files (particularly text files, and engaging in the process of writing to them). The problem is, I have begun to find that both the codes I copy for myself from the book into a compiler, as well as the codes from the "Answer Sheet" sort of folder that came with a disc contained within the book, do not work.

The big problem with this of course is that, although the author does a great job of explaining the code and how it works in the "How It Works" part of every section, after any given coding exercise, I find that I learn best by analyzing a code as I run the .exe, examining each process bit by bit by comparing what appears on the console output, to how it is handled within the code itself.

Let me give you an example.

#include <iostream>
#include <fstream>
using namespace std;

int get_int(int default_value);
char name[20];

int main() {
	char filename[81];
	int n;
	int age;
	int recsize = sizeof(name) + sizeof(int);


	cout << "Enter file name: ";
	cin.getline(filename, 80);

	// Open file for binary read and write.	

	fstream  fbin(filename, ios::binary | ios::in | ios::out);
	if (!fbin) {
		cout << "Could not open file " << filename;
		return -1;
	}

//  Get record number to write to.

	cout << "Enter file record number: ";
	n = get_int(0);

	// Get data from end user.

	cout << "Enter name: ";
	cin.getline(name, 19);
	cout << "Enter age: ";
	age = get_int(0);

	// Write data to the file.

	fbin.seekp(n * recsize);
	fbin.write(name, 20);
	fbin.write(reinterpret_cast<char*>(&age), sizeof(int));
	fbin.close();
	system("pause");
	return 0;
}

// Get integer function
// Get an integer from keyboard; return default
//  value if user enters 0-length string.
//
int get_int(int default_value) {
	char s[81];

	cin.getline(s, 80);
	if (strlen(s) == 0)
		 return default_value;
	return atoi(s);
}

This code is from the "answer sheet" folder. Meaning of course that this is the code written by Brian (or someone else, I don't know) but should theoretically be accurate.

Both this code and my own have the same problem.

The program should supposedly create a binary output file with data on the user's name and age.

This is my first time doing things with binary files, and I'm already finding them somewhat complex. Admittedly, having the exercises not work for me is greatly impairing my ability to understand the idea behind certain processes, how to use certain syntax, and more importantly, how these bits of syntax, and things (in this example) such as binary file writing could be at all useful in more productive working programs.

Does anyone have any suggestions on how I could get through this problem?

If anyone is curious, I do have on my computer two other C++ for beginners books by the titles of "C++ - How to program" and "C++ primer fifth edition".

Thanks.

Link to comment
Share on other sites

Recommended Posts

  • 0

The code above works for me in Dev-C++.

All I did was create a new console application project. I don't think you can simply open the 3 files and hit compile. Then I just added the 3 files to the project and hit compile. The rest is done for you.

Link to comment
Share on other sites

  • 0
Hmm. I really don't have a clue how to do what you're trying to explain.

All Dr_Asik was suggesting was that you try using a more up-to-date IDE as Dev-C++ hasn't been upgraded in years. That said though, for what you need it for, it works.

Did you try creating a project like I said above?

Link to comment
Share on other sites

  • 0
Hmm. I really don't have a clue how to do what you're trying to explain.
I'm saying use VC++ express 2008, don't waste time with Dev-C++. It won't take long before you can leverage its superior debugger, documentation and project management options, making it easier to learn C++ in the process. You'll also be acquainted with the single most used IDE in the industry. You'd be surprised at the number of positions that list familiarity with Visual Studio as a plus or even requirement.

That said, I'm a bit off-topic here. :)

Link to comment
Share on other sites

  • 0

What I was saying was just that I didn't know how to do what you were explaining with the headers.

That said, after playing around with it, I successfully made one header file with the prototype for a function, and it's definition, and was able to use it in another project.

I take it you can create large header files and use them to support whatever functions you may want to use, and have it referred to from any number of projects, correct?

As for why I use dev-c++, I use it for the following reasons:

A.) The debugger is clean and easy to read. If I'm missing a } or a ;, it tells me where, and I can easily fix it. Whereas Visual c++ 2008 seems to be cluttered with a lot of junk that I really don't feel necessary in the debugging process. Maybe it is, and I'm not at a point where it matters, but it's a lot more confusing than necessary at my current level.

B.)Dev-C++ creates two files. A .cpp and a .exe. As far as I've been concerned right now, those are the only things I've ever had to get out of a program. I feel that visual c++'s folder-containing-data method is confusing considering the fact that I really don't know what to do with it all.

C.)Dev-C++ has a very simple and novice-friendly UI. I really appreciate that as, I don't really NEED an abundance of advanced options at this point, where I am still just focusing on learning the basic syntax, and methodology of the C++ language.

That said however, I am trying to use visual c++ more. I just feel that it's better to move into it slowly, after I figure out how to actually take advantage of the many tools and options that visual C++ has to offer, but only after I can really do so while making use of the c++ language itself. It's a growth thing, perhaps.

Link to comment
Share on other sites

  • 0

Hello everyone.

I'm back right now because I have a question relating to classes.

Again, the book I am using to learn c++ has been pretty good, but since getting into the last 5 chapters or so, on the topic of objects, there have not been many opportunities to really put class creation to practice. There have been many examples but it's mostly been theory explanation for some parts, and then just explanations of different syntax on constructors, operators, etc...

So I decided to try to put some class ideas to use by writing a little part of a "game" if you could call it that.

Basically, the player just attacks a dummy until it loses it's health.

#include <iostream>
using namespace std;

//Class -> Dummy
class dummy {
private:
	int health;
public:
	//Constructor
	dummy() {set(100);}

	//Functions
	void set(int fullhealth) {health = fullhealth;}
	void sit() {cout << "The dummy does nothing\n\n";}
	int get_health() {return health;}
	int hpcheck();
}

//Class -> Player
class player {
private:
	int health;
	int damage;
public:
	//Constructor
	player() {set(100, 15);}

	//Functions
	void set(int maxhealth,int maxdamage) {health = maxhealth; damage = maxdamage;}
	int attack();
	int get_damage() {return damage;}
}

int main() {
	player you;
	dummy dum;
	int c;
	char move[16];

	cout << "You are now fighting a dummy with 100 health points. \n";
fight:
	cout << "Please type in your command from one of the following. \n\n";
	cout << "attack\n\n";

movechoose:
	cin.getline(move, 15);
	c = move[0];
	if (c != 'a' || c != 'A') {
		cout << "Improper imput.\n";
		cout << "Please enter a new one.\n\n";
		goto movechoose;
	}
	else {
		you.attack();
		cout << "Dummy's Health is " << fail.hpcheck();
		system ("pause");
	}
	goto fight;

	return 0;
}

int player::attack() {
	cout << " You: I am attacking!\n";
	cout << "Dummy's health reduced by " << you.get_damage() << endl;
	int dumhealth = dum.get_health() - you.get_damage();
	cout << "Health remaining is " << dumhealth << endl << endl;
}

int dummy::hpcheck() {
	if (dum.health < 0) {
		dum.health = 0;
		cout << dum.get_health() << endl;
		cout << "Congradulations!\n";
		cout << "You have successfully defeated a helpless dummy!\n\n";
		return 0;
	}
	if (dum.health != 0 && dum.health !< 0) {
		return dum.health;
	}
}

Some problems I am supposedly having are that there are issues with:

A. -Main- not returning a integer, even though I have return 0; set at the end.

B. "you" not being declared in function attack();

C. "dum" not being declared for first use in a function.

I remember from my book that a lot of manipulation of class information involves some complicated arguments, like the copy constructor's class_name(class name const &source) sorts of things, or class_name(class_name other); etc...

Anyways, I wrote this when I was pretty tired, too, so don't be surprised if I made some simple mistakes.

Can anyone help me better understand what I am trying to do with these classes, and how to use them in general?

Link to comment
Share on other sites

  • 0

First don't use gotos because it leads to arbitrary and difficult to understand control flow.

Second, do yourself a favor and split that code in separate files. Class declarations go in header files with an include guard; implementation goes in a cpp file of the same name. Here you really need:

main.cpp

dummy.h

dummy.cpp

player.h

player.cpp

There are lots of small issues that will make the compiler emit strange errors. Here are a few I could spot:

- no semicolon after class declarations - leads to really nasty compiler errors

- in dummy::hpcheck(), you attempt to use an object called dum, but it's neither a member of the class nor a locally defined variable. You declare a variable of the same name in main(), but that's a local, i.e. it's scoped to that method and unaccessible outside of it. Really if you want access to class members, since you're inside the class, you can use them directly:

int dummy::hpcheck() {
	if (health < 0) {
		health = 0;
		cout << health << endl;
		cout << "Congradulations!\n";
		cout << "You have successfully defeated a helpless dummy!\n\n";
		return 0;
	}
}

Really you can never do dummy.health because health is private, so it's only accessible by methods of the class itself.

- !< isn't an operator. Maybe you wanted to do !(health < 0)? Or simply (health >= 0)?

Ok now that we got some syntactical details cleared up, let's see what you were trying to do.

You want to represent a player attacking a dummy. For this you create a player that has a health and damage rating, and a dummy that just has a health.

What you're missing is that in order for the player to attack a dummy, the player must somehow get a reference to that particular dummy. For example, the method attack could take a reference to a dummy as a parameter:

int player::attack(Dummy&amp; dummy) {
	cout &lt;&lt; " You: I am attacking!\n";
	cout &lt;&lt; "Dummy's health reduced by " &lt;&lt; damage &lt;&lt; endl;
	int currentDummyHealth = dummy.get_health();
	int newDummyHealth = currentDummyHealth - damage;
	dummy.set(newDummyHealth);
	cout &lt;&lt; "Health remaining is " &lt;&lt; newDummyHealth &lt;&lt; endl &lt;&lt; endl;
	return newDummyHealth;
}

I hope that helps.

Oh, and don't bother about copy constructors, that's a more advanced topic. You really need to get the syntactical basics right first.

Edited by Dr_Asik
Link to comment
Share on other sites

  • 0

Ah, I see what you're saying here.

I also noticed some of my silly mistakes, like the lack of semicolons this morning. Sleepiness does awful things to people, huh?

That help on the class explanations is a big help, too. Thanks a bunch. I'll revise what you said for a while and try to get more accurate class productivity working.

Thanks again.

Link to comment
Share on other sites

  • 0

Overusing this thread again for the topic of c++ and books and whatnot...

I have a question regarding languages.

I have almost finished with my book for the basics of C++, and I think I've done pretty well with it so far as I've been able to do new, more advanced things as I practice, and with the help of everyone here at neowin.

One thing I've seen a lot lately is discussion of switching to C# from C++. It seems a lot of people are doing it and a lot of people recommend it.

My questions are as follows:

1. Should I, in my programming novice-hood, pursue switching to C# as soon as I am done with the basics of C++, and have that basic understanding of programming?

2. Is C# as big of a deal as people make it seem? It seems that C# is a higher level language that can essentially do anything efficiently.

3. With regards to the future, about four years down the road or so, which language would it be better to know?

I've been considering moving into C# because of all the positive attitudes towards it, but I wonder how necessary that is, how beneficial it would be, and whether or not I'd be better to "master" C++ first, or not.

Thanks.

Link to comment
Share on other sites

  • 0

That's a can of worms... :p

They both have their uses, for instance you don't see websites in C++ and you don't see PS3 games in C#. They are tools optimized for different scenarios. My rule of thumb is to always use C# unless there's a need for direct control of memory and/or need for ultimate performance.

As a beginner I learned both C++ and C#. Superficially they are very similar, under the hood they work completely differently. Learning both deep enough to realize the fundamental differences is, IMO, essential to becoming a good programmer.

EDIT: answering your specific questions now...

1. It's a good path, but a good one would also be to start making a larger program in C++ and becoming more proficient with it immediately. I recommend learning another very different language (such as C#) earlier than later, but any learning is good. In short, stay with C++ for a while if you wish, but do learn C# at some near point in the future, definitely.

2. C# is a well-designed language :heart: that allows you to do a lot of things that are painful in C++ remarkably more quickly, and with much less chances for errors. It is not however suited for any kind of application. C++ can do anything, but at the cost of always being painful to use. So again, if you can use C#, please do, but C++ is necessary in several cases.

3. 4 years down the road, both C# and C++ programmers will be able to make comfortable livings. Those who know both will always have a better understanding of what they do and better employability.

Edited by Dr_Asik
Link to comment
Share on other sites

  • 0

Hm.. So there's a lot of benefits in ether.

By what you've described, it seems that C# might be the better language to learn as a beginner, generally speaking.

I think perhaps I'll give it a go. Now that I have the fundamentals down in C++, I might try to delve more deeply into C#, and perhaps some day I'll come back to C++ and learn a little more of it when I find it necessary.

Thanks for the excellent input once again.

Link to comment
Share on other sites

  • 0

I have another question regarding books, I'm afraid.

I was just quickly wondering what the next step in learning a language would be after going through a "book of the basics" to learn the more primitive syntax?

This applies to either C++ and, should I decide to start it, C#.

Thank you all for all your help until now,

I truly appreciate it.

Link to comment
Share on other sites

  • 0

For C++, you may want to read:

Effective C++

More Effective C++

Effective STL

Also once you have learned C#, read a book on design patterns, either

Head First Design Pattern (in Java, but it's so similar to C# it doesn't matter)

or

Design Patterns: Elements of Reusable Object-Oriented Software (mainly in C++, much more formal and boring, and old)

An excellent read for any programming language is

Code Complete 2nd edition

And eventually you need to read something on data structures and algorithms, but I don't have any particular book recommendations. ( I read both Data Structures and Algorithms for Game Developers and Data Structures and Algorithm Analysis in Java and thought neither was more than decent ).

Edited by Dr_Asik
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.