Forum

> > Off Topic > C++ Tutorial
Forums overviewOff Topic overviewLog in to reply

English C++ Tutorial

128 replies
Page
To the start Previous 1 2 3 4 5 6 7 Next To the start

old Re: C++ Tutorial

Flacko
User Off Offline

Quote
If you're running windows you can use system("pause"); it will display the "Press any key to continue..." text so you can read the output.

old Re: C++ Tutorial

archmage
User Off Offline

Quote
Thanks Flacko though when this is done (you will find out soon what it is) it must be multi-platform.
And I have edited Lee's to make mine store the data.
Spoiler >

Edit this is similar to above except it writes the data to a file and instead of opening text2.txt it opens text2.txt.txt how to fix?
<removed source> nvm I fixed it, but it leaves a ÿ at the end of the file
Spoiler >

Edit nvm I fixed it
I really need a command that works as table.insert with dynamic memory is there a way or a function?
edited 4×, last 22.07.10 06:01:30 am

old Re: C++ Tutorial

Flacko
User Off Offline

Quote
Well, you have vectors.
Otherwise you would have to use pointers:
You have to create a new pointer that points to a bigger array, you copy the old content, add the new one, delete the old pointer and make it point to the new one.

BTW: Your code is a mess, try to make it look more or less like this:
1
2
3
4
5
6
7
if (condition)
{
	while(condition)
	{
		dostuff();
	}
}

That way you can comment out lines like if (condition) easier without having to comment out the braces, which may turn into a headache if your project gets bigger.

old Re: C++ Tutorial

archmage
User Off Offline

Quote
ugh Well how to get the length of arrays and dynamic memory and what do ya mean by copy is there a function or will I have to do it?

old Re: C++ Tutorial

Flacko
User Off Offline

Quote
A common way to do so is
1
(sizeof yourarray)/sizeof(yourtype)

The sizeof operator returns the size in bytes, so you divide it and get the value.
1
2
int* a = new int[4];
cout << (sizeof a/sizeof(int));

Yes you have to loop through and assign the new value
1
2
3
4
for(int i=0; i<oldsize; i++)
{
	newarray [i] = oldarray[i];
}

old Re: C++ Tutorial

archmage
User Off Offline

Quote
Thanks I will work on that sometime. But if I create a function what type should it return if it returns an array the type of the array?

old Re: C++ Tutorial

Flacko
User Off Offline

Quote
Well, I wouldn't make a function that returns arrays because this is forbidden in plain C.
But it should return a char* or wathever type you are using, still, you need to know the size of the old array because "sizeofing" pointers always returns 4 (pointers point to memory addresses so they use 4 bytes atleast in my 32-bit windows).

BTW, you might want to read on typecasting: http://www.cplusplus.com/doc/tutorial/typecasting/

This example concatenates a c string to another one
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <cstdlib>
#include <iostream>
using namespace std;

char he[] = "he"; // 'h','e',0

char* concatenate(char* oldstr, char* addstr, int sizeofold, int sizeofadd)
{
	char* newstr = new char[sizeofold + sizeofadd];
	for(int i=0; i<sizeofold; i++)
	{
		newstr[i] = oldstr[i];
	}
	for(int i=0; i< sizeofadd; i++)
	{
		//here we overwrote the null character from the old string, if we were using other type
		//for something different we would have declared int i=1.
		newstr[i+sizeofold] = addstr[i];
	}
	newstr[sizeofold + sizeofadd] = 0; //We add again the terminating null character
	return newstr;
}

int main(int argc, char *argv[])
{
	cout << concatenate(he, "llo dude", 2,8) << '\n';
	system("PAUSE");
	return EXIT_SUCCESS;
}

I'd recommend you to use vectors since they support different types and and have less bugs than my code
http://www.cplusplus.com/reference/stl/vector/
edited 1×, last 22.07.10 08:00:39 am

old Re: C++ Tutorial

archmage
User Off Offline

Quote
What is wrong I get an error at line 18 with ifstream file (input)
Do not re-write or fix just tell me what is wrong.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <new>
using namespace std;

int main() {
	while (true) {
	     stringstream data;
		string* file_data;
		string input("text.txt");
		int l(0);
		cout << "Enter a file to copy: ";
		getline(cin, input);
		if (input == "exit")
			break;
	     ifstream file (input);
	     if (file.is_open()){
	      while (!file.eof())
	           data << (char) file.get();
				file_data = new (nothrow) string[l];
				file_data[l] = data.str();
				l++;
	      file.close();
	     }
	     else cout << "Error: Can not open the file: \""+input+"\".";
	   	ofstream file2;
	   	string filename("");
	   	for ( int i = 0; i<input.length(); i++ )
	   		if ( input.substr(i,i) != "." )
	   			filename = filename+input.substr(i,i);
	   		else
	   			filename = filename+" (copy).";
		file2.open(filename);
		int i(0);
		for ( i = 0; i<l; i++)
			if ( i < l-1 )
				file2 << file_data[i] << endl;
			else
				file2 << file_data[i].substr(0,file_data[i].length()-1);
		file2.close();
	}
     return 0;
}

old Re: C++ Tutorial

Flacko
User Off Offline

Quote
Use ifstream file(input.c_str()) instead.
It looks like ifstream doesn't support C++ strings, only the C ones.

old Re: C++ Tutorial

Lee
Moderator Off Offline

Quote
As flacko said, ifstream expects a native string for the filename. Just pass in the .c_str() methodcall

old Re: C++ Tutorial

archmage
User Off Offline

Quote
Okay thanks.
Edit:
The name gets screwed up. text.txt becomes extt.t.txttxtxtt, but the correct data is written to the file.

Edit:
I am guessing it is impossible to return arrays? This won't work it stops at return na;
Spoiler >
edited 3×, last 23.07.10 07:42:36 am

old Re: C++ Tutorial

Lee
Moderator Off Offline

Quote
if you pass in a reference of the object to the function, you can directly manipulate the object. Of course, c/c++ code isn't meant to be elegant or minimalistic. (unless you settle for the boost libs, in which case you might as well just use Java or C# to code your app)

@filename
Assuming that you've done all of the proper changes with string to c string, apply the following patch:

Replace
1
2
3
4
5
for ( int i = 0; i<input.length(); i++ )
	if ( input.substr(i,i) != "." )
		filename = filename+input.substr(i,i);
	else
		filename = filename+" (copy).";

with the following

1
2
3
4
5
int dot = filename.find(".");
if (dot != filename.npos)
	filename.replace(dot,1,".copy.");
else 
	filename += ".copy";

And then change it according to your preferences.

Glad to see that you're making so much progress within such a short interval of time. Keep it up and it'll become second nature after a short while.

old Re: C++ Tutorial

archmage
User Off Offline

Quote
Thanks. I tried what I think you meant, but it still won't work. I tried returning a pointer to the new array, but it gets an error at the line where I reference the pointer to the new array (na).
Spoiler >


Edit:
How can a create a textarea a window and add text to that textarea? Or where can I learn GUI programming?
edited 2×, last 24.07.10 09:47:40 pm

old Re: C++ Tutorial

Flacko
User Off Offline

Quote
I recommended you to use Nokia's Qt in a PM. Forget it, the download is about 200MB.

However, GTK+ is not so big.
You can download the pack if you are running Dev-C++ by clicking the 'Tools' tab and then in 'Check for updates/packages', select devpaks.org as your devpak server and click on the 'Check for updates' button.
Once your Dev has loaded all the paks mark the pak named 'GTK (the gimp toolkit)' and click on download selected.
Then it will start to download the pack and install it, they usually include examples and tutorials.

You might also be interested in taking a look to this tutorial:
http://library.gnome.org/devel/gtk-tutorial/2.21/

old Re: C++ Tutorial

archmage
User Off Offline

Quote
I just put it in Dev-C++\includes that is where the other stuff goes?

old Re: C++ Tutorial

Flacko
User Off Offline

Quote
Yeah, you put the files under the include in your dev/include folder and so with lib and bin (if any)

Edit: Forget what I said, I will set it up in my PC first so I can give you better instructions, the GTK library seems to use many other libraries, too many.

Edit once again:
Ok, this is what you have to do:

Download the file I posted.

Uncompress all the files in C:\GTK

Download this template I made so we won't have to rewrite all the include directories which is an epic pain in the ass: http://www.mediafire.com/?g339useqgbhkhne

Open Dev-C++, go to File->New->Project->'GUI' tab->GTK project->Compile->Run

This is what we've got until now, don't expect much more:
http://img571.imageshack.us/img571/7668/dibujolem.png
It gives us a nice little resizeable window with buttons and a console that all it seems to do is throw weird warnings when we rightclick our project in the taskbar.

->If it comes out that you're not able to use your C:, open the .template file with notepad and replace every C:\GTK with D:\GTK or whatever.
edited 2×, last 25.07.10 12:51:25 pm

old Re: C++ Tutorial

archmage
User Off Offline

Quote
Thanks flacko. I still need that insert function to work.
I tried returning a pointer again, but it still fails.
More >

old Re: C++ Tutorial

Lee
Moderator Off Offline

Quote
C++ is memory centric so you will need to reallocate the memory. (In a more straightforward term, the realloc call basically makes sure that the supplied pointer is not padded by blocks that are currently used by the program)

Here's an example that inserts a number if it's odd else 0:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int* add(int* list, int* ssize){
	*ssize += 1;
	if(!(list = (int* )realloc(list,sizeof(int)*(*ssize))))
		cout << "Failed to reallocate memory\n";
	list[*ssize-1] = (*ssize)*((*ssize)&1);
	return list;
}

int main(){
	int* list = NULL;
	int ssize = 0;
    
	for(int i=0;i<100;i++) list = add(list,&ssize);
	for (int i=0;i<ssize;i++) cout << i << " " << list[i] << endl;
    
 	return 0;
}

This is the most important line:
1
2
if(!(list = (int* )realloc(list,sizeof(int)*(*ssize))))
		cout << "Failed to reallocate memory\n";

We defined list as a int* initialized to null. Note the distinction between a flat out pointer and an array:

A pointer defined as <type>* identifier is a variable pointer. This means that its address can be changed.

An array defined by <type> identifier[] is a constant pointer. This means that its address cannot be changed, but which doesn't mean that the content of the address cannot be changed.

Now here's the tricky part about this, we could have actually passed list as a reference like ssize into an void add(int** list, int* ssize); But we must then allocate both the container and the container's container in order for this to work. Since references are consts, we have to somehow cast it into a variable pointer (which in turn makes it lose its reference) so for brevity's sake, we just reassign the value of the list as the return value of the function add.

Some other oddities:
We could've also write this:

1
2
3
4
5
6
7
int* add(int* list, int* ssize){
	int size = (*ssize += 1);
	if(!(list = (int* )realloc(list,sizeof(int)*size)))
		cout << "Failed to reallocate memory\n";
	list[size-1] = size*(size&1);
	return list;
}

As the the default operator= method for all native C++ objects are associative (implying that they return the left-value of the assignment)

Output:
1
2
3
4
5
6
7
8
9
10
11
0 1
1 0
2 3
3 0
4 5
5 0
6 7
7 0
8 9
9 0
...
To the start Previous 1 2 3 4 5 6 7 Next To the start
Log in to replyOff Topic overviewForums overview