Tellalca 19 Posting Whiz in Training

Hey there;

I'm having trouble with fork() and wait() functions.

In the code below I'm trying to create a child process and first let the child process do its work then parent process finish execution. I use wait() function in the parent process but the output shows that child process finishes last.

Expected Output: Lines with "*" may vary in ordering of course

Parent process is waiting child...*
In child process! *
Child completed its task.

Actual Output:
Parent process is waiting child...
Child completed its task. //How can child complete its task withour printing to the screen first ?
In child process!

#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <sys/wait.h>

using namespace std;

int main()
{
	pid_t pid;

	pid = fork();

	if(pid < 0)//Error occurs
	{
		cout << "Error creating child process." << endl;
		exit(-1);
	}
	else if(pid == 0)//Child process
	{
		cout << "In child process!" << endl;
	}

	else if(pid > 0)//Parent process
	{
		cout << "Parent process is waiting child..." << endl;
		wait();
		cout << "Child completed its task." << endl;
		return 0;
	}
Tellalca 19 Posting Whiz in Training

I think it is a program.

I programmed a life game when I was studying data structures and algorithms. It has interesting combinations when you enter as input you will see interesting shapes when the game runs.

Tellalca 19 Posting Whiz in Training

A pointer is really an adress of s space in memory, no more. What confuses you may be usage of the pointers.

I like studying iterators before pointers. That makes things cristal clear.

Btw Accelerated C++ and C++ Primer Plus 4th edition rulez.

Tellalca 19 Posting Whiz in Training

Hey;

I am trying to keep a data file but I'm getting confused with the sizeof(char) = 2 bytes. I understand that it is a unicode char but why does class BinaryReader's function ReadChars(int count) function just increases the streams position by count bytes ?

If that is not clear here is what I ask;

sizeof(char) = 2 OK!

when I say

BinaryReader fileReader = new BinaryReader(File.Open(fileName, FileMode.Open));
fileReader.ReadChars(100); // Here it increases the current stream position by 100 bytes , but it should be sizeof(char) * 100 = 200 bytes
Tellalca 19 Posting Whiz in Training

Should we design a game for you ? If so, I can't.

If you design a game, you will probably end with all those concepts. It is very hard to develop even a simple game, without using abstraction, encapsulation, composition etc.

Polymorphism can take a little time to think about though.

Tellalca 19 Posting Whiz in Training

Okay, I placed the file to the desktop. That solved my problem.

Tellalca 19 Posting Whiz in Training

Hey;

I am developing a console game in C#. I wanted to create a file called "accounts.bin" to hold players accounts information.

So when I try to create or access the file the program halts and throws an exception called "UnauthroizedAccessException". I tried to put the file into the "C:\" directory, then "C:\ProgramFiles(x86)\" directory but nothing changed.

Here below is my AccountsFile class, I just implemented the constructors. How can I grant the application with the needed authorization ? Is there anything wrong with the code, because this is the first time I am working with File IO.

public class AccountsFile
    {
        #region Fields
        string _fileName;
        int _numberOfAccounts;

        #endregion

        #region Properties
        public string FileName { get; set; }
        public int NumberOfAccounts { get; set; }
        public DateTime LastModifiedDate { get; set; }

        #endregion

        #region Constructors
        public AccountsFile() 
        {
            NumberOfAccounts = 0;
            FileName = "\\Program Files (x86)\\BrainSalad\\info\\accounts.bin";
            BinaryWriter file = new BinaryWriter(File.Create(FileName));
            file.Write(NumberOfAccounts);
        }

        public AccountsFile(string iFileName)
        {
            FileName = iFileName;
            try
            {
                BinaryReader file = new BinaryReader(File.Open(FileName, FileMode.Open));
            }
            catch (Exception ex)
            {
                BinaryWriter file = new BinaryWriter(File.Create(FileName));
                file.Write(0);
            }
            BinaryReader existingFile = new BinaryReader(File.Open(FileName, FileMode.Open));
            NumberOfAccounts = existingFile.ReadInt32();
        }
        #endregion
    }
Tellalca 19 Posting Whiz in Training

Ok sorry for not being clear. Actually I want to be able to wait a character input from user and when it exceeds 10 seconds bypass Console.Read() and print an error message.

//I start a timer here
//When it exceeds 10 seconds stop Console.Read() function and move on
Console.Read();

if(timer > 10)
   Console.Write("You couldnt answer in 10 seconds.");
Tellalca 19 Posting Whiz in Training

Hey;

In my application I want to count number of seconds while the application is waiting for the user input.

I think I should use another thread but I never worked with multithreading. Is there an easier way ?

Tellalca 19 Posting Whiz in Training

Hey;

I want to store string, ConsoleColor pairs like

dataStructure.Add(new KeyValuePair<string, ConsoleColor>("Red", ConsoleColor.Red))

I tried List but it did not seem to work;

List<KeyValuePair<string, ConsoleColor>> colorList;
            colorList.Add(new KeyValuePair<string, ConsoleColor>("Red", ConsoleColor.Red));
            colorList.Add(new KeyValuePair<string, ConsoleColor>("Yellow", ConsoleColor.Yellow));
            colorList.Add(new KeyValuePair<string, ConsoleColor>("Green", ConsoleColor.Green));
            colorList.Add(new KeyValuePair<string, ConsoleColor>("Blue", ConsoleColor.Blue));
            colorList.Add(new KeyValuePair<string, ConsoleColor>("White", ConsoleColor.White));

with the error "An unhandled exception of type 'System.NullReferenceException' occurred in BrainSalad.exe".

Can you help me with this issue?

Tellalca 19 Posting Whiz in Training

Use some structs, classes, functions and loops in your game. You cant write a game like writing a story. You have to reuse the code you have already written like,

printMenu() // function that prints menu 
struct player
{
  int hp;
  int damage;
  int magic;

}// carries information about your character
Tellalca 19 Posting Whiz in Training

When you define "int Array[100];" actually you are defining a pointer to the first element of the array. So if you "cout << Array" you will see this will print the adress of the first element. It is the same as "cout << &Array[0]". So simply Array is a pointer.

When passing an array to a function you can pass it using "int Array[]" or since it is a pointer you can pass it as "int *Array". In the function you should not try to decleare the same array again like "int Array[100]". You passed the argument so you can should use it without declaring again.

double average(int array[], int sizeOfArray)
{
double avg; // Your return value
int sum = 0;// Sum of all the elements of array
for(int i =0; i < sizeOfArray; i++)// Iterate through array
{
sum += array[i]; // Calculate the sum
}
avg = (double)sum / sizeOfArray; //Cast to double to get a double after calculation
return avg;
}
Tellalca 19 Posting Whiz in Training

Hey thanks;

I meant cross platform, platform independent game developing. Do we have to use OS API to create a window ? Can not Graphics libraries create window ?

For example when you use Allegro you enter the sizes of the window you want to create and it creates it for you. You do not use any OS dependent commands / system calls there.

So how does that library do that if you have to use the OS API to create a window ? Does that library uses OS API too?

When I'm creating a window with Allegro under Windows, does the Allegro's function create a handle and then call CreateWindowEx() itself under the hood?

I may not have been very clear, sorry for that.

Tellalca 19 Posting Whiz in Training

Airport management system, wow! Please don't make us crash into another plane.

Tellalca 19 Posting Whiz in Training

Trick is that don't try to get two things at the same time. Find the prime numbers between 1 - 100 then go to the algorithm that you give.

Calculate the primes.
You have the list of prime.
Go from 1 through 100
If your number is in the list of prime
Print prime
Else
Calculate the numbers prime factors by dividing it to the primes starting from 2
Hold the primes that successively divides the number
Print them

Tellalca 19 Posting Whiz in Training

You may want to define a constructor and a copy constructor.

Tellalca 19 Posting Whiz in Training

You may ask it in the Microsoft forum since what you are asking is about Windows programming.

Tellalca 19 Posting Whiz in Training

You can't, I am not talking about mixing your code with some tools. Getting access to the memory is the responsibility of the OS. If the OS give permission than you can't hide.

Tellalca 19 Posting Whiz in Training

If you are having problem with converting text '1' into integer 1 then look at the ASCII table. There you see the decimal value of character '1' is 49.

There if you read '1' into an integer variable you are holding 49. If you just decrease that by 48 you get 1. It goes same for 2 and 3 and .. too.

Tellalca 19 Posting Whiz in Training

Isn't there anyone who knows about OS API programming?

Tellalca 19 Posting Whiz in Training

Look for '\n' or whatever new line character is in your OS.
Count them, they will tell you which line you are in.
When you reach the line you want, then do whatever you want.

Use seekp(), tellp(), get(). You may actually use binary mode when opening file if you know the structure of the file.

I think it will make so much faster using a buffer there since you are reading sequentially. If it was random access it probably won't matter.

Tellalca 19 Posting Whiz in Training

Make the error corrections about arguement list and then compile and repost the errors and the new code here.

Tellalca 19 Posting Whiz in Training

It's very hard to read your code since you have no indentation there and also we do not know even what your problem is.

How can you want us to fix your problem if you don't tell the problem ?

Tellalca 19 Posting Whiz in Training

I will answer your question but firstly you'd better use private keyword for xPos and yPos, it's absolutely identical what you have done but it is a good programming habit and make it easier to read your code for someone else.

Your problem is that when you say "Shape 1" you declare a shape but on the right handside "new Shape(5,5);" returns you a pointer to newly allocated Shape object. So you need to either use

1 -

Shape 1(5,5);                // Call the corresponding constructor

2 -

Shape *1 = new Shape(5,5);   // New allocates memory space, constructs the Shape object on that space, and returns you the adress of the newly constructed Shape object
Tellalca 19 Posting Whiz in Training

Hey;

I want to get into some game programming just for fun and to improve my C++ and software development experience.

For now I developed some Console Applications as anyone would do.

Now the question is this; do I need to know how to use WinApi or POSIX in order to develop some games?

If Yes; then how is it possible to make xplatform games?

If No; then is it the Graphics or other libraries that communicates with operating system to create GUI?

Thanks.

Tellalca 19 Posting Whiz in Training

Hey SgtMe;

If you know how to install allegro to use with VS2010 can you please explain. I downloaded allegro and looked everywhere in it to read a document about how to install for VS2010 but found nothing.

Tellalca 19 Posting Whiz in Training

Hey;

I want to be able to use VS2010 and still pass command line arguments to it somehow.

When I am building an application that needs to use argv[], I need to compile it and run it from the command line. That is becoming boring sometimes especially when I want to use the VS2010 debugger too.

So please show me a way to pass arguments to use with combination Ctrl- F5 ( build and run ).

Tellalca 19 Posting Whiz in Training

You can read it using standard fstream I think, since its plain text file. You dont need "visual"C++.

Tellalca 19 Posting Whiz in Training

This one is called Fibonacci Series

Tellalca 19 Posting Whiz in Training

I found it. I needed to add "fileo.flush();" just after trying to write down. That was a silly mistake.

Everyone be careful about flushing, lol.

Tellalca 19 Posting Whiz in Training

Nope, that didn't work for me. I'm getting upset, what the hell is going on in that file !?

Output:
41-858993460
67-858993460
34-858993460
0-858993460
69-858993460
24-858993460
78-858993460
58-858993460
62-858993460
64-858993460
5-858993460
45-858993460
81-858993460
27-858993460
61-858993460
91-858993460
95-858993460
42-858993460
27-858993460
36-858993460

bool CreateRandFile(char* fileName, int numberOfValues)
{
	ofstream fileo(fileName, ios::out | ios::binary );
	ifstream filei(fileName, ios::in | ios::binary);
	if(!fileo.is_open())
	{
		cerr << "Error on creating file: " << fileName;
		return false;
	}

	else if(!filei.is_open())
	{
		cerr << "Error on reading file: " << fileName;
		return false;
	}

	else
	{
		for(int i = 0; i < numberOfValues; i++)
		{
			int random = rand() % 100;
			cout << random;
			fileo.write((char *)&random, sizeof(int));

			int read;
			filei.read((char *)&read, sizeof(int));
			cout << read << endl;	
		}
	}
	return true;
}
Tellalca 19 Posting Whiz in Training

Hey;

I am having problem with the read and write functions in fstream. They need to have a const char * to read or write from/to buffer. I need to work with integers.

Here what happens:

for(int i = 0; i < numberOfValues; i++)
		{
			
			int random = rand() % 100;
			cout << random;
			file.write((char *)&random, sizeof(int));

			int read;
			file.read((char *)&read, sizeof(int));
			cout << read;
		}

This code writes a value and tries to read it back. But the results don't match. What is the problem, and what is the solution of course :)

Tellalca 19 Posting Whiz in Training

You can dissassemble the code and see the assembly code there. There is almost no way turning the assembly code back into the C++ or another language.

Tellalca 19 Posting Whiz in Training

Read Thinking in C++. It's freely available in web and one of the best sources you can find. You can download the ebook at: http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html .

Tellalca 19 Posting Whiz in Training

Hey;

I have an assignment but I'm having trouble because I don't know almost any assembly. I have figured out something but please help me if I have mistakes, and with the 3rd formula.

Using knowledge from previous weeks, write assembly programs which calculate the given formulas:
a)Sum (i=1 to n) i
b)Mult (i=1 to n) i
c)Mult (i=0 to n) (2*i + 1)
n = <Last digit of Student ID> mod 5
If n = 0, then n = 5

Please help me with the c) . Here what I have so far:

;part a

ld r0, #0h	; load 0 to r0
ld r1, #1h	; load 1 ro r1

loop1:
add r0, r1	; add r1 to r0 and store on r0
inc r1		; increase r1 by 1
eq r1, #5h	; compare r1 == 5
jr z, loop1	; if not true go loop1 again

;part b

clr r0
ld r1, #1h
ld r2, #1h

loop2:
ld r0, r2
mult rr0
inc r2
eq r2, #5h
jr z, loop2
Tellalca 19 Posting Whiz in Training

Good advice from David. Even you cannot understand this code after not seeing it for a week.

Tellalca 19 Posting Whiz in Training

Thanks guys. I thought since it is a member of the class, it will be placed on the heap.

Tellalca 19 Posting Whiz in Training

Debug and see what is the error. Tell us about the error so we can help. We are not compilers.

Tellalca 19 Posting Whiz in Training

Btw you cannot seperate the implementation and the decleration if you are working with a template class.

Tellalca 19 Posting Whiz in Training

You may product two random numbers generated by the rand() function to get a bigger random number. That's just an example. You can create your own random number generator function.

Tellalca 19 Posting Whiz in Training

You can find a project which I made last year like yours. you can check it on the Projects page of www.operatasarim.com.

Download the source code and see if it helps.

Tellalca 19 Posting Whiz in Training

When creating a new project in VS 2010 try creating an empty project when the program asks.

I think you are learning from Deitel's How to Program C++. That is a good book, but have a look at Accelerated C++ and other books whose names can be found in the C++ Books sticky thread here on Daniweb C++ category.

Tellalca 19 Posting Whiz in Training

I won't read your whole code but it's obvious from the error you get that you are trying to write/read to/from a memory location which you dont have access.

You are most probably having problem with pointers. Try debugging, see if you are trying to access to a memory location which your program does not own.

Tellalca 19 Posting Whiz in Training

You can't tell what your problem is. Don't expect us to reply to your problem.

Tellalca 19 Posting Whiz in Training

Did you hear about <fstream> class from the standart library.

It defines some basic file input/output operations for binary and text files, but you have to give the file names to the program, there is no folder manipulating operations defined in this class.

Tellalca 19 Posting Whiz in Training

Hey;

I'm practicing with template classes. When I declare a user-typed destructor for this template class, the program freezes and needs to be closed explicitly.

Obviously, in the destructor, I am trying to release the memory allocated to hold the coordinates[3] array. What is the problem with declaring a user-typed destructor?

#ifndef POINT_H
#define POINT_H

template<class T>
class Point
{
    typedef T value_t;

public:
    Point(){}
    Point(T coor[])
    {
        coordinates[0] = coor[0];
        coordinates[1] = coor[1];
        coordinates[2] = coor[2];
    }
    Point(const Point& p)
    {
        coordinates[0] = p.coordinates[0];
        coordinates[1] = p.coordinates[1];
        coordinates[2] = p.coordinates[2];
    }

    ~Point() //The problem occurs here...
    {
        delete[] coordinates;
    }
private:
    value_t coordinates[3];
};
#endif

code:

#include <iostream>
#include "Point.h"

using namespace std;

int main()
{
    double arg[3] = {0,1,2};
    Point<double> myPoint(arg);
    myPoint.~Point();
    return 0;
}
Tellalca 19 Posting Whiz in Training

How is it possible to delete a byte ( char, int, double .. ) from a text file ?

Suppose that the file.txt contains :"110Hello". And I want to delete "110" from the file leaving only the "Hello" part.

How to do this without reading the whole file into the memory and then rewriting the edited data ?

Thanks.

Tellalca 19 Posting Whiz in Training

I want to write and read a Student struct to/from a file. The program works weird . Sometimes reads 52 elements, sometimes 1 element. I couuld not see what the problem is. Help please.

int main()
{
	FILE *deneme = openBinaryFile("C:\\text\\text.txt");
	Student me = {"Mert","Akcakaya",200611004, 0};
	Student you = {"Default", "Default", 111111111, 0};
	insertRecord(deneme, me);
	readRecord(deneme,&you,1);
	printf("%d %d %s %s", you.deleted, you.studentID, you.name, you.surname);
	deleteRecord(deneme,1);
	printf("isDeleted = %d", isRecordDeleted(deneme,1));
	return 0;
}
int insertRecord(FILE *file, const Student student)
{
	unsigned long int studentID[1];
	int deleted[1];
	int check = 0;

	fseek(file,0,SEEK_END);
	studentID[0] = student.studentID;
	deleted[0] = student.deleted;

	check += fwrite(deleted, sizeof(int), 1, file);
	check += fwrite(studentID, sizeof(unsigned long int), 1, file);
 	check += fwrite(student.name, sizeof(char), 30, file);
	check += fwrite(student.surname, sizeof(char), 50, file);
	fflush(file);
	return (check == 82);
}

int isRecordDeleted(FILE *file, int position)
{
	int deleted[1];
	fseek(file, totalStudentSize * (position-1), SEEK_SET );
	fread(deleted, sizeof(int), 1, file);
	if(deleted[0] == 1)
	{
		printf("File was deleted");
		return 1;
	}
	else 
		return 0;
}

int readRecord(FILE *file, Student* student, int position)
{
	int check = 0;
	unsigned long int studentID[1];
	int deleted[1];
	fseek(file, totalStudentSize * (position-1), SEEK_SET);
	if( !feof(file) )//Should skip the statement when the position is bigger then the biggest position in the file, but does not...
	{
		check += fread(deleted, sizeof(int), 1, file);
		check += fread(studentID, sizeof(unsigned long int), 1, file);
		check += fread(student->name, sizeof(char), 30,  file);
		check += fread(student->surname,  sizeof(char), 50, file);
		student->deleted = deleted[0];
		student->studentID = studentID[0];
	}
	else
		printf("Not accurate position for reading!", stderr);
	
	return ( check …
Tellalca 19 Posting Whiz in Training
string encryption(string plainText, int key)

{

string temp;

for(int i=0; i <plainText.length();i++)
{
[COLOR="Red"]temp+=[/COLOR] plainText[i] + key;
}
return temp;

}

Maybe changing temp+= plainText[i] + key; to temp[i] = plainText[i] + key; would work... The same logic goes with the decryption one.

Tellalca 19 Posting Whiz in Training

I think you have lots of problems there.

First what do you do with "city" after you get it with :getline(cin,city);

Second you are searching substring in bigstring, but you did not initialize those strings? What you are doing is searching zero in zero ?

Third you are reading every line in the file cities.txt. What is the point of doing that? You may want to search the file for the substring instead i think, and display the matching cities.