scandalz.net
 
 
 
BETA (Google AJAX Search)

Programming C/C++

I'm going to put some source code snippets and references here as I create and/or come accross them.

illegal else without matching if

by Bart_sg at 19:19 PM, 03/09/2010

#include <iostream>
#include <iomanip>
#include <string>
#include <ios>

using std::string;
using std::streamsize;
using std::setprecision;
using namespace std;



int main()
{
        double Ib,I,V,P,F,pf,In;
        unsigned short int type;
        cout<<"Please select the type of power supply\n";//Allows the user to choose between single or three phase
        cin>>type;
        switch(type)
        {
        case 1:cout<<"You have chosen a single phase power supply\n";
                break;
        case 2:cout<<"You have chosen a three phase power supply\n";
                break;
        default:cout<<"Invalid choice please try agin\n";
                break;
        }
        cout<<"Please enter the value of I\n";//the value of the load current
        cin>>I;
        cout<<"Please enter the value of V\n";//the value of the input volatge
        cin>>V;
        cout<<"Please enter the value of F\n";//the frequency
        cin>>F;
        cout<<"Please enter the value of the power factor\n";//the power factor
        cin>>pf;
       
       
        if(type=1)
        {
                cout<<"Ib in Single phase is\n" << setprecision(4)
                <<(V*I)/V/I/pf
                <<setprecision(4)<<endl;
       
        else
                cout<<"Ib in Three phase is\n" << setprecision(4)
                <<(V*I)/(1.732*V*pf)
                <<setprecision(4)<<endl;
        }

       
       
        return 0;
}

very simple code help. beginner

by rcmango at 19:00 PM, 03/09/2010

Hello, i am very interested in the c++ language, i decided to make my own small program and test how arrays work with classes with private variables and private operations and then calling them any way i'd like from the main function.

a very big reason about this is probably because i'm trying to pass by reference, which i thought was necesary if i'm keeping the changes everywhere within the program, and using a void function. If there is any advice as to coding better, i'd like those too.
there are syntax errors, line 20 only, please help me :)

////.header file for class arrays.
#include <string>
using namespace std;

class arrays {
private:
    string hold;
    int keep;
    int raekwon[];
public:
void Talk(string&, int&);

};

///this is my arrays header function
#include "arrays.h"


void arrays::Talk(hold&, keep&) {
///this creates the array based from the size parameter
    raekwon[keep];
   
    //this displays the information
    cout << "okay, you are feeling " << hold << " today.\n";
    cout << "also, the size of the array you asked for is " << keep << "\n";
    cout << "the elements in the array are: " << raekwon << "\n";


}

///this is the main function

#include "arrays.h"
#include <iostream>
#include <string>

using namespace std;

main()
{
    arrays a;
    string feelings;
    int array_size;
   
    cout << "how are you feeling today?\n";
    cin >> feelings;
    cout << "\n" << "what size array you want?\n";
    cin >> array_size;

    a.Talk(feelings&, array_size&);
    return 0;
}

//////////////////////////////////////////////////

Sum of odd numbers

by marcelomg at 18:53 PM, 03/09/2010

Hello,
I'm stuck with this code and I can't figure out how to make it work. I need to get the Sum of Odd numbers from an array. For some reason it returns 0.
I'm new to programming, so any help would be appreciated, thanks.
Here it is:

#include <iostream>
using namespace std;


const int MAX = 10;
int a[ MAX ] = {1,2,3,4,5,6,7,8,9,10};

int smallResult = 0;

int sumOdd( int MAX[], int n )
{       
        if ( n == 0 )
                return 0;
        else{
                int smallResult = sumOdd( MAX + 1, n - 1 );
                return smallResult + MAX[ 0 ];
                }

}
int main ()
{
        cout << "Sum of Odd is: " << smallResult << endl;
        return 0;
}

Varible loss during Blackjack

by kratosaurion at 18:38 PM, 03/09/2010

Hi guys and gals, 1st post here! Woot!
With that out of the way, I need some help with this steaming fresh BJ program. I need to write functions for the yes deal and no deal options, but the player total seems to get messed up somehow and when a new card is added after the fist two, the total becomes the second card + the first card. I need a little help figuring out what would be the problem.

Code is here:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include "drawmore"
using namespace std;

int main()
{
        //blackjack
        int you, deal, toty, totd, hold, yhold;
        char opto, agn;

        unsigned seed = time(0);
        srand(seed);
        do
        {
                toty = 0;
                totd = 0;
                hold = 0;
                you = 0;
                deal = 0;
                yhold = 0;

                cout << "\n\n\n\n\nWeclome to C++ Blackjack!\n\n";
                you = 1 + rand() % 10;
                cout << "Your first card is: " << you << endl;
                toty += you;
                you = 1 + rand() % 10;
                cout << "Your next card is: " << you << endl;
                toty += you;
                cout << endl;

                deal = 1 + rand() % 10;
                hold = deal;
                cout << "Your dealers first card is: " << deal << endl;
                totd += deal;
                deal = 1 + rand() % 10;
                cout << "Your dealers next card is hidden! " << endl;
                totd += deal;

                yhold = toty;

                cout << "\nYour current total is: " << toty << endl;
                cout << "The house's current total is: " << hold << " plus a hidden card!" <<  endl;

                for ( ; toty < 21;)
                {
                cout << "Deal? (Y/N) ";
                cin >> opto;

                if (opto == 'N' || opto == 'n')
                {
                        if (toty > totd || toty == totd)
                        {
                                cout << "You win!\n"<< toty << " is more than or equal to " << totd << endl;
                                break;
                        }
                        else
                        {
                                cout << "The house wins!\n" << totd << " is more than " << toty << endl;
                                break;

                        }
                }


                if (opto == 'y' || opto == 'Y')
                {
                        drawmore (you, toty);
                }
        cout << "Play again? (Y/N) ";
        cin >> agn;
        }while (agn == 'Y' || agn == 'y');

        return 0;
}




And the function looks like this:

#include <iostream>
using namespace std;

void drawmore (int you, int toty)
{
                        you = 1 + rand() % 10;
                        cout << "Your next card is: " << you << endl;
                        toty += you;
                        if (toty == 21)
                        {
                                cout << "21! You win!";
                                break;
                        }
                        else if (toty < 21 && toty > 1)
                        {
                                cout << "Your total is: " << toty << endl;
                        }
                        else
                        {
                                cout << toty << " = Bust! You lose!" << endl;
                                break;
                        }

                        opto = 0;
}

Container class problem

by icelantic at 17:40 PM, 03/09/2010

I am working on an assignment which is a container class that uses an array to hold strings. We must use dynamic memory, and can only use cstring class functions, no objects can be strings. So we must use char arrays. Anyways my problem is that whenever i run my program it instantly crashes and I can't seem to find why, any help would be greatly appreciated.


/*
 * stringArray.h
 *
 *  Created on: Mar 2, 2010
 *      Author: Jacob
 */

//Constructor for the stringArray class
// stringArray(const size_t max_size = DEFAULT_SIZE);
//
//
//Copy constructor stringArray(const stringArray& source);
//
//Destructor ~stringArray();
//
//bool addString(const char new_string[]);
// adds a new string in the bag.
// POSTCONDITION: returns true if string was successfully added to the bag, false otherwise
//
//bool removeString)const char old_string[]);
// removes one occurrence of old_string from the bag.
//POSTCONDITION: returns trus if successful; false otherwise
//
//size_t removeAll(const char old_string[]);
//removes all occurrences of old_string from the bag.
//POSTCONDITION: removes the strings and then returns the number of strings removed
//
//bool substitute(const char old_string[], const char new_strin[]);
//Replaces one occurrence of old_string with new_string
// POSTCONDITION: one is replaced and true is returned, if there are no occurences of old_string
// or the function failed somehow, false is returned instead
//
//size_t substituteALL(const char old_string[], const char new_stringn[]);
// Replaces all the occurrences of old_string with new_string
//POSTCONDITION: Returns the number of strings replaces.
//
//size_t size()
// returns the total number of strings in the bag
//
// bool is_string(const char cur_string[]) const;
// returns true if cur_string is present in the bag, false otherwise
//
// size_t occurrences(const char cur_string[]) const;
// returns the number of occurrences of cur_string in the bag
//
// void printStringArray() const;
// Prints out all strings in the stringArray object, one string per line
//
// void pringSortedStringArray() const;
// prints out all strings in the stringArray object, one string per line, ina sorted order from least to greatest
//
// overloaded operators
//
// stringArray operator+ (stringArray& x, stringArray& y)
//
// stringArray operator- (stringArray

#include <iostream> // Provides ostream and istream
#include <cstdlib> // Provides ostream and istream

using namespace std;


namespace csci2270_assignmentTwo
{

        class stringArray
        {
                public:
                        stringArray(const size_t max_size = 10);
                        stringArray();
                        stringArray(const stringArray& source);
                        ~stringArray();
                        bool addString(const char new_string[]);
                        bool removeString(const char old_string[]);
                        size_t removeAll(const char old_string[]);
                        bool substitute(const char old_string[], const char new_strin[]);
                        size_t substituteAll(const char old_string[], const char new_string[]);
                        size_t size();
                        bool is_string(const char cur_string[]);
                        size_t occurrences(const char cur_string[]);
                        void printStringArray();
                        void pringSortedStringArray() const;


                        bool stringArray::operator == (const stringArray &right);
                        bool stringArray::operator!=(const stringArray &right) const;
                        stringArray stringArray::operator +=(const stringArray &right);
                        friend stringArray operator+(const stringArray& left, const stringArray& left);

                private:
                        size_t count;
                        size_t max_size;
                        char** storage;
        };

}


/*
 * stringArray.cxx
 *
 *  Created on: Mar 2, 2010
 *      Author: Jacob
 */


#include <iostream>
#include <cstdlib>
#include <cstring>
#include "stringArray.h"
using namespace std;

namespace csci2270_assignmentTwo
{

        stringArray::stringArray(const size_t max_size)
        //creates a dynamic array that is the size of the max size
        //sets count equal to zero
        {
                char** storage = new char* [max_size];
                for(int i = 0; i < max_size; i++)
                {
                        storage[i] = "\0";
                }
                count = 0;
        }

        stringArray::stringArray()
        {
                char** storage = new char* [10];
                for(int i = 0; i < 10; i++)
                {
                        storage[i] = "\0";
                }
                count = 0;
        }

        stringArray::~stringArray()
        {
                for(int i = 0; i < max_size; i++)
                {
                        delete storage[i];
                }
                delete storage;
        }


        stringArray::stringArray(const stringArray& source)
        {
                count = source.count;

                for(int i = 0; i < max_size; i++)
                {
                        strcpy(storage[i], source.storage[i]);
                }

        }

        bool stringArray::addString(const char new_string[])
        {


                int length = strlen(new_string);
                for(int i = 0; i < max_size; i++)
                {
                        if(storage[i] != "\0")
                        {
                                storage[i] = new char[length];
                                strcpy(storage[i], new_string);
                                count++;
                                return true;
                        }
                }

        }



        bool stringArray::removeString(const char old_string[])
        {


                for(int i = 0; i < max_size; i++)
                {
                        if(strcmp(storage[i], old_string) == 0)
                        {
                                delete storage[i];
                                count--;
                                for(i; i < (max_size - 1); i++)
                                {
                                        strcpy(storage[i], storage[i+1]);
                                }
                        }
                }

        }
        size_t stringArray::removeAll(const char old_string[])
        {
                for(int i = 0; i < max_size; i++ )
                {
                        removeString(old_string);
                }
        }
        bool stringArray::substitute(const char old_string[], const char new_string[])
        {
                for(int i = 0; i < max_size; i++)
                {
                        if(strcmp(storage[i], new_string) == 0)
                        {
                                delete storage[i];
                                int length = strlen(new_string);
                                storage[i] = new char[length];
                                strcpy(storage[i], new_string);
                                return true;
                        }
                }
                return false;
        }
        size_t stringArray::substituteAll(const char old_string[], const char new_string[])
        {
                size_t ammount = 0;
                for(int i = 0; i < max_size; i++)
                {
                        if(strcmp(storage[i], new_string) == 0)
                        {
                                delete storage[i];
                                int length = strlen(new_string);
                                storage[i] = new char[length];
                                strcpy(storage[i], new_string);
                                ammount++;
                        }
                }
                return ammount;
        }

        size_t stringArray::size()
        {
                size_t size;

                for(int i = 0; i < max_size; i++)
                {
                        if(storage[i] != "\0")
                        {
                                size++;
                        }

                }
                return size;
        }

        bool stringArray::is_string(const char cur_string[])
        {
                for(int i = 0; i < max_size; i++)
                {
                        if(strcmp(storage[i], cur_string) == 0)
                        {
                                return true;
                        }
                }
        }

        size_t stringArray::occurrences(const char cur_string[])
        {
                size_t occur;

                for(int i = 0; i < max_size; i++)
                {
                        if(strcmp(storage[i], cur_string) == 0)
                        {
                                occur++;
                        }
                }
                return occur;
        }

        void stringArray::printStringArray()
        {
                for(int i = 0; i < count; i++)
                {
                        cout << storage[i];
                        cout << endl;
                }
        }

        void printSortedStringArray()
        {

        }

        stringArray stringArray::operator +=(const stringArray &right)
        {
                int i = 0;
                stringArray new_bag(max_size + right.max_size);

                for(int i = 0; i < max_size; i++)
                {
                        strcpy(new_bag.storage[i], storage[i]);
                }
                for(i; i < (max_size + right.max_size); i++)
                {
                        strcpy(new_bag.storage[i], right.storage[i]);
                }
                return new_bag;
        }

        bool stringArray::operator == (const stringArray &right)
        {
                if(max_size != right.max_size)
                {
                        return false;
                }

                for(int i = 0; i < max_size; i++)
                {
                        if(strcmp(storage[i], right.storage[i]) != 0 )
                        {
                                return false;
                        }
                }
                return true;
        }

        bool stringArray::operator!=(const stringArray &right) const
        {
                if(max_size != right.max_size)
                {
                        return true;
                }
                for(int i = 0; i < max_size; i++)
                {
                        if(strcmp(storage[i], right.storage[i]) != 0 )
                        {
                                return true;
                        }
                }
                return false;
        }
        stringArray operator+(const stringArray& left, const stringArray& right)
        {
                stringArray temp = left;
                int i = 0;

                for(i; i < temp.max_size; i++ )
                {
                        strcpy(temp.storage[i], right.storage[i]);
                }

                return temp;


        }




}

"sketches" in c++

by mebob at 16:29 PM, 03/09/2010

Hi, i am doing my mom's c++ for engineering class, and doing a project for her, i noticed something in the extra credit section of her project directions. it says to add graphics to represent what variables the users are entering. in this one, it is about beam deflection, and it says for extra credit to put a diagram of the beam and the parts labeled with the variables. How would i go about doing this?

ERROR, Counting Characters In a Linked List

by crozbme at 16:25 PM, 03/09/2010

I am trying to count the characters in a linked list.
I am receiving a compiler error when this function is tested...

**invalid types `char[int]' for array subscript **

int slist::count_c(char c) const
{
  slistelem* temp = h;
  int count = 0;
  for (int i = 0; i != '\0'; i++)
      if (temp == c[i])
        count ++;
  return count;
}

How can I fix this function to properly display desired results?
With a function call such as

cout << l.count_c('b') << endl;

Question and Request

by M.FARAG at 15:57 PM, 03/09/2010

I have downloaded a library from this site that deals with Matrix and Complex........Does it do this correctly???
http://www.zenautics.com/matrixdoc/index.html
if so I want to use this library to get the inverse matrix of of a matrix consists of a complex elements
how can I do this???
If it is a wrong one
can any one help me to get a library do this function please
thanks in advance

Help with table summary for bank account.

by Chris-16 at 15:00 PM, 03/09/2010

I am trying to set up a 12 month table summary in a bank account program. The problem I have is I am trying to figure out how to set it up correctly. Here is my class and application from the bank account:

Here's the class part:

class SavingsAccount
{
        //Data declaration
        private:
                int accountNumber;
                double balance;
                double rate;
                string depositChoice;
                string withdrawalChoice;
                double deposit;
                double withdrawal;
                double endBalance;


        public:
                //Methods declarations/prototypes
                void setAccount(int,double,double);
                double getBalance();
                string deposChoice();
                string withdrawChoice();
                double depositBalance();
                double withdrawalBalance();
                double getEndingBalance();       
               
};

//Methods implementation

//Constructor method:  a special method used to
//initialize an object's state
//The constructor is automatically called and executed
//when the object is instantiated

void SavingsAccount::setAccount(int accNo, double startBalance, double startRate)
{
        accountNumber = accNo;
        balance = startBalance;
        rate = startRate;
}
double SavingsAccount::getBalance()
{
        cout << "\nThe current balance in your account is $"
                << balance << endl;

        return balance;
}
string SavingsAccount::deposChoice()
{
        cin.ignore();
        cout << "\nWould you like to make a deposit(Y/N): ";
        getline(cin, depositChoice);
       
        return depositChoice;
}
double SavingsAccount::depositBalance()
{
                if (depositChoice == "Y")
                {
                        cout << "\nEnter amount to deposit:  ";
                        cin  >> deposit;
                        return deposit;
                }       
                else if (depositChoice == "N")
                {
                        cout << "\nOk no deposit I see!"
                                << endl;
                }       
}
string SavingsAccount::withdrawChoice()
{
        cin.ignore();
        cout << "\nWould you like to make a withdrawal(Y/N): ";
        getline(cin, withdrawalChoice);
       
        return withdrawalChoice;
}
double SavingsAccount::withdrawalBalance()
{
        if (withdrawalChoice == "Y")
        {
                cout << "\nEnter amount to withdrawal:  ";
                cin  >> withdrawal;
                return withdrawal;
        }       
        else if (withdrawalChoice == "N")
        {
                cout << "\nOk no withdrawal I see!"
                        << endl;
        }
}

double SavingsAccount::getEndingBalance()
{
        if (depositChoice == "Y" && withdrawalChoice == "Y")
        {
                endBalance = balance + deposit - withdrawal;
                cout << "\nThe ending balance for your account is $"
                        << endBalance << endl;
                return endBalance;
        }
        else if (depositChoice == "Y" && withdrawalChoice == "N")
        {
                endBalance = balance + deposit;
                cout << "\nThe ending balance for your account is $"
                        << endBalance << endl;
                return endBalance;
        }
        else if (depositChoice == "N" && withdrawalChoice == "Y")
        {
                endBalance = balance - withdrawal;
                cout << "\nThe ending balance for your account is $"
                        << endBalance << endl;
                return endBalance;
        }
        else if (depositChoice == "N" && withdrawalChoice == "N")
        {
                endBalance = balance;
                cout << "\nThe ending balance for your account is $"
                        << endBalance << endl;
                return endBalance;
        }
}


Here's the cpp/application part:

#include <iostream>
#include<string>
#include <iomanip>
using namespace std;

#include "SavingsAccount.h"
//file is located in project directory

int main()
{
        cout << "Welcome to the bank today!" << endl;

        SavingsAccount newAccount;
        newAccount.setAccount(111, 4000.0, .004);
        newAccount.getBalance();
        newAccount.deposChoice();
        newAccount.depositBalance();
        newAccount.withdrawChoice();
        newAccount.withdrawalBalance();
        newAccount.getEndingBalance();

        cout << "\nMONTH        START BALANCE        INTEREST        END BALANCE\n";
        int month;
        double interest = 0.0;
        double endBalance = 0.0;
        double rate = 0.0;
        double newEndBalance = 0.0;
        month = 1;
        while (month <= 12)
        {
          interest = endBalance * rate;
          newEndBalance = endBalance + interest;
          cout << month << endBalance << interest << newEndBalance <<    endl;
          month++;
        }
        cout << "\nThanks for stopping by the bank, have a nice day!\n" << endl;
        return 0;       
}//END MAIN

The output of the table is supposed to be like this:

Month Starting Interest Ending
# Balance Earned Balance
1 4000.00 16.00 4016.00
2 4016.00 16.06 4032.06
3 ... ... ...
4
5
6
7
8
9
10
11
12
The start balance of is table is the ending balance after I deposited/withdrew funds, the interest part I have to multiply the balance to the rate(.004) and the end balance is where I have to add the balance to interst.

The table part of it is the last part of the cpp part, I just wanted to know what to put there to make it come out correctly. Thanks greatly for the help.

first program compile error

by heliodoros at 14:18 PM, 03/09/2010

hello guys this is my first attempt in C++ and i am getting an error :(
the programs is made to read 20 numbers and find how many of them are even (like 2,4,6,20,40)
#include <iostream>

using namespace std;
int c[20];
int s = 0;
int i = 1;
int main()
{

  cout << "Enter the numbers followed by the ENTER key\n";

      loop:
            cin >> c[i];
            if(c[i]%2=0) //line with error
            {s++;}
            i++;
            if (i<=20) goto loop;

  cout << "done!\n Number of values: ";
  cout << s;
  system("PAUSE");
return 0;
}

and the error:
In function `int main()'
line 14: error: non-lvalue in assignment

getline problem

by clutchkiller at 12:08 PM, 03/09/2010

void NewCustInfo(CustData &cust)
{
        cout << "Customer Name: ";
        getline(cin, cust.name);

}

CustData is a structure that is declared, and the name data member of that struct is of type string. For some reason when I call this function(there are no compile errors), it displays the cout statement, but then completely skips over the getline function. Any ideas?

Thanks

Format

by charqus at 10:57 AM, 03/09/2010

Is there in C++ , a function like this ?

http://wiki.sa-mp.com/wiki/Format

How to allocate memory dynamically on stack ?

by tajendra at 10:40 AM, 03/09/2010

I read some time back that memory operation on stack is much faster than heap. With this information the first thing came into my mind was that if we get a way to allocate memory dynamically on stack it would surely help us to optimize memory operation cost. I started searching for it and finally I found one such way ;).
Before going into its detail let’s take a look at dynamic memory allocation on heap.

Generally when it comes to dynamic memory allocation new/malloc the well known calls
Comes into mind. They help us to dynamically allocate memory on the heap.

For e.g.
int FunctionA()
{
  char* pszLineBuffer = (char*) malloc(1024*sizeof(char));
    …..
  // Program logic
    ….
  free(pszLineBuffer);
  return 1;
}

Above code would allocate 1024 bytes on heap dynamically. After the complete use of variable szLineBuffer, we
need to free memory also (free/delete can be used for it). So, one has to keep track of deallocation call,
else memory leak will get introduced.

Now coming back to our question, is there any way by which we can allocate memory dynamically on stack.So the answer is yes. We can allocate variable length space dynamically on stack memory by using function _alloca. This function allocates memory from the program stack. It simply takes number of bytes to be allocated and
return void* to the allocated space just as malloc call. This allocated memory will be freed automatically on function exit.
So it need not to be freed explicitly. One has to keep in mind about allocation size here, as stack overflow exception may occur. Stack overflow exception handling can be used for such calls. In case of stack overflow exception one can use _resetstkoflw() to restore it back.

So our new code with _alloca would be :-

 int NewFunctionA()
{
  char* pszLineBuffer = (char*) _alloca(1024*sizeof(char));
    …..
  // Program logic
    ….
  //no need to free szLineBuffer
  return 1;
}

Now let’s check out what will be the advantage of _alloca over new/malloc :-
1) We have saved overhead of new/malloc.
As _alloca() got very little overhead of allocating memory on stack.
2) No need to free memory explicitly. So, deallocation cost will be zero.
3) If function like FunctionA() got multiple time in your program it may cause heap memory fragmentation on a long run,
Which would be saved with NewFunctionA() as stack memory never goes fragmented.


Now let’s check out what will be the disadvantage of _alloca over new/malloc :-
1) One has to be cautious while using alloca for huge blocks.
2) Its scope is limited to a function call.
3) As stack overflow is not a standard C++ exception, one hast to use structured exception handling for it.


One can also right ask that :-
"_alloca function is deprecated because a more secure version is available.
_malloca : Allocates memory on the stack. This is a version of _alloca with security enhancements."

My Answer to this question is :-
"malloca does not allocates memory from stack always, it will go to heap depending on _ALLOCA_S_THRESHOLD value. Also you need to manage its deallocation flow. _alloca is best suited to be used when you need small chunk of memory but very frequently and if chuck size is not guaranteed to be small _malloca can be used.
One more point _malloca always allocates memory from the heap in DEBUG mode. So you get diffrent behavior in release and debug."

I hope you enjoyed this post.
-Tajendra

NOTE:- I have added hyperlink in accordance to rule, which says :-
"Self-promotion links are permitted within forum signatures provided they do not contradict with any other sitewide rules, such as inappropriate language or content." So is it ok?

Basic Encryption

by GPPK at 09:28 AM, 03/09/2010

Hi Guys,

I'm really interested in C++ and am currently making a basic Text based poker game.

on a sideline to this does anyone know any simple encryption code or where to start when doing this? For instance taking a text file (.txt or even .doc?) and creating your own encryption key and encrypting and decrypting.

Also wonder about password protection and things like this.

Cheers,

G.

help with a c++ project?

by acemaster3 at 09:20 AM, 03/09/2010

1. Manipulate dynamic pointers and arrays of pointers
2. Use sorts, strings, searches and string functions.

Procedure:

1. Your new software engineering group is hired for its first paying project to develop a console application to demonstrate a possible user interface for a next generation MP3 player.
2. Your C++ program will prompt the user to input up to 20 (controlled with a global constant int) names of Artists whose songs will be loaded into the MP3 player. No artist name will be more than 80 characters (including the null terminator). Each entry needs to be loaded (strcpy would be nice) into a dynamic string created with the new keyword.
3. Each of the pointers to the strings of the Artists names needs to be stored in an array – yielding an “array of pointers”.
4. The array needs to be sorted in a separate void function such that the first alphabetical artist name should be stored in the [0] entry of the array, the next in the [1] entry etc.
5. After the array is sorted, call a void function passing the array and the number of entries in the array and print out the artists. The list should be sorted correctly.
6. After printing out the artists, prompt the user for a search string in main(). Call a void function to search through the strings pointed to by your array and return (through a call by reference) an array of references which contain the search string. The search should be case in sensitive. If you searched, for example, on “bob”, you would return references to “Bob Dylan” and “The bobs”.
7. If there were valid references returned from your search, call the same print function as in step 5 above and print out the artists that had a match in the search. If there were no valid references, cout a message to the user. You should allow for multiple searches via re prompting.
8. At the end of your program be sure to iterate through your newly allocated strings and be sure to return the allocated memory back to the operating system.

9. Here’s an example of input and output:

Enter artist name: Grateful Dead
Another artist? (y,n): y
Enter artist name: Lucinda Williams
Another artist? (y,n): y
Enter artist name: Third Eye Blind
Another artist? (y,n): y
Enter artist name: Bob Marley
Another artist? (y,n): y
Enter artist name: Metallica
Another artist? (y,n): n
Sorted Artist List:
Bob Marley
Grateful Dead
Lucinda Williams
Metallica
Third Eye Blind
Enter search string: ll
References:
Lucinda Williams
Metallica
Search Again? (y,n): y
Enter search string: a
References:
Bob Marley
Grateful Dead
Lucinda Williams
Metallica
Search Again? (y,n): y
Enter search string: x
Sorry. No references in database for search on: "x"
Search Again? (y,n): n
Press any key to continue

Help with using CreateMutex() for Multithreading Newbie!

by dshiells at 09:03 AM, 03/09/2010

Basically I am trying to learn multithreading in C++. Platform: Windows XP. So far so good but I want to make sure I'm using mutex correctly. It compiles and runs as expected, but just wanted to make sure I use the CreateMutex() function in the correct place.

Thanks!

Here's my code (if it helps, I'm using Dev-C++):

#include <cstdlib>
#include <windows.h>
#include <iostream>
#include <fstream>

using namespace std;

DWORD WINAPI myThreadFunc1(LPVOID param);
DWORD WINAPI myThreadFunc2(LPVOID param);
int readFile();

HANDLE hMutex;

int main(int argc, char *argv[])
{
hMutex = CreateMutex(NULL, false, "fileMutex");

HANDLE myThread1 = CreateThread(NULL, 0, myThreadFunc1, NULL, 0, NULL);
HANDLE myThread2 = CreateThread(NULL, 0, myThreadFunc2, NULL, 0, NULL);

system("PAUSE");
return EXIT_SUCCESS;
}

DWORD WINAPI myThreadFunc1(LPVOID param)
{
readFile();
}

DWORD WINAPI myThreadFunc2(LPVOID param)
{
readFile();
}

int readFile()
{
WaitForSingleObject(hMutex, INFINITE);

ifstream myReadFile;
myReadFile.open("data.txt");
char output[100];
if(myReadFile.is_open())
{
while(myReadFile.getline(output, 100))
{
cout << output;
}
cout << endl;
}
myReadFile.close();

ReleaseMutex(hMutex);

return 0;

}

Tutorials

by mattjbond at 07:57 AM, 03/09/2010

I am curious about how to post or have published tutorials. I have searched the forum but the latest information I cna find is years out of date. Any help here?

Mouse movement

by Zhrate at 07:28 AM, 03/09/2010

Hello, I've been searching for hours now for a way to do mouse movement in a program while its minimized, so I can do other stuff etc while the mouse movements are doing their thing in the target window.

Could anyone please give me a direction how to do this?



Zhrate

BIT FILEDS CONCEPT in C++

by srinidelite at 07:07 AM, 03/09/2010

hello..

this is srini... is any one clear me the concept of BIT FIELDS........and what is necessity to use?????

explain the below program..........i hope i can get a good reply from the great members

// BIT FILED //

#include<iostream.h>
#include<conio.h>
struct word
{
unsigned w0:1,w1:1,w2:1,w3:1,w4:1,w5:1,w6:1,w7:1,w8:1,w9:1,w10:1,w11:1,w12:1,w13:1,w14:1,w15:1,w16:1,w17:1,w18:1,w19:1,w20:1,w21:1,w22:1,w23:1,w24:1,w25:1,w26:1,w27:1,w28:1,w29:1,w30:1,w31:1;
};
union set
{
word m;
unsigned u;
};
void main()
{
set x,y;
x.u=0x0f100f10;
y.u=0x01a1a0a1;
x.u=x.u|y.u;
cout<<"element 9="<<((x.m.w9)?"true":"false")<<endl;
}

OUTPUT

ELEMENT 9 =TRUE

copy a 1D vector into a 2D vector !?

by habib_parisa at 05:55 AM, 03/09/2010

Dear all,

I am trying to understand a C++ code.
In one part of the code a one dimensional vector is copied into a two dimensional vector.
I do not understand at all how such thing can work. But compiler is quite ok with that.

#define TOTAL_STEPS 120
#define NUMBER_DECISION_VARIABLES 5
int main(){

vector<vector<double> > DV;

vector<double> grid ( TOTAL_STEPS,0.0);

vector<double>temp ( NUMBER_DECISION_VARIABLES,0.0);

temp[0] = 0.0;
temp[1] = 0.65;
temp[2] = 0.2;
temp[3] = 0.6;
temp[4] = 0.3;

DV.resize( grid.size(), temp); // <<<<<<------------------ here ??


return 0;
}

DV[][] is 120*120 and temp[] is 5, How does it work?

string stream, operator<<, special handling for user class

by TimeFractal at 04:58 AM, 03/09/2010

Hello,

I need to simulate a stream which behaves exactly like a ostringstream, except when handling objects of type color. What is the best way to do this?

user.display() << color() << "Name: " << color(color::Red)   << setw(10) << left  << str_name << endl
              << color() << "Date: " << color(color::Green) << setw(10) << right << int_date << endl;
should display the same as...
user.display() << color() << "Name: " << setw(10) << left  << color(color::Red)   << str_name << endl
              << color() << "Date: " << setw(10) << right << color(color::Green) << int_date << endl;


I programming a telnet server that has to display text in color. The color codes are ANSI escape sequences ie characters. These characters when passed to ostringstream via << mess up setw() formatting alignment.

I need a mechanism to receive and process escape sequence characters from operator << without passing them on to ostringstream. What is the best way to do this?

I could write a wrapper that emulates ostringstream but then I would have to provide every overloaded << function. That's a lot of busy work. There has to be a better way.

Last night, I tried to inherit public ostringstream and provide operator << for my color class. I realized that would not work because ostringstream operator<< returns a reference to ostringstream and not my class. Could I overload operator << in color() to return console()? How would that translate into code?
class console: public std::ostringstream
{
public:
  console& (operator<<) ( color &c )
  {
      std::cout << "color: " << c.i << std::endl;
  }
  // wont work if color is not the first obj passed to the stream
};

Next I tried to emulate the entire ostringstream interface. This works except for setw, which gives me compile error "error: declaration of 'operator<<' as non-function" in g++.
#include <iostream>
#include <iomanip>
using std::setw;

class console
{
private:
  std::ostringstream oStr;

public:
  console& (operator<<) ( color &c )
  {
      std::cout << "color: " << c.i << std::endl;
  }
  console& (operator<<) ( std::string &s )
  {
      std::cout << "string: " << s << std::endl;
      oStr << s;
  }

  console& (operator<<) ( setw p )
  {
      std::cout << sw << "setw: " << std::endl;
      oStr << p;
  }

  void Render()
  {
      std::cout << oStr.str();
  }
};

ideas? Thanks in advance.

Help with adding date to filename

by bakwanyana at 04:46 AM, 03/09/2010

#include <stdio.h>
#include <time.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main ()
{
  ofstream file;
  stringstream ss;
  time_t rawtime;
  struct tm * timeinfo;
  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  char g[30];
  char buffer[10];
  itoa(timeinfo->tm_mday,buffer,10);
  strcat(g,buffer); 
  strcat(g,"-");
  itoa(timeinfo->tm_mon+1,buffer,10);
  strcat(g,buffer);
  strcat(g,"-");
  itoa(timeinfo->tm_year+1900,buffer,10);
  strcat(g,buffer);
 
  file.open((const char*)g, ios_base::app);
  if (!file) cout<<"error"<<endl;
  file<<"success!"<<endl;
  file.close();
  system("PAUSE");
  return EXIT_SUCCESS;
}

The file does not want to be opened - Can anyone help me?

Disable access to internet - windows and Linux

by evstevemd at 03:56 AM, 03/09/2010

Hi all,
how can I disable internet in windows/Linux machine. I want to disable completely and enable it at will using C++
Thanks

OpenGL text printing weirdness help please

by Nicky4815 at 03:33 AM, 03/09/2010

Working on my pacman project I have come across something strange. Im using the outline font method from NeHe and have used the code from there for text printing. When I copied it to my main method and texted it worked fine. But a lot of my objects need to print text so I decided to move the code to a text printing object. I didn't change anything in the text code but now that it's been moved when glPrintf() is called the symbol printed is one less than the one asked (e.g: "w" prints "v", "!" prints a space) I have tried to rectify it by adding 1 to the variables in the method but nothing works.

It's not a big problem as I can work around it but for printing the score it is a big problem.

Here are the h and cpp files for it:
//Header file for text printer
#ifndef TEXTPRINTER_H_
#define TEXTPRINTER_H_

#include <windows.h>                // Header File For Windows
#include <math.h>                        // Header File For Windows Math Library
#include <stdio.h>                        // Header File For Standard Input/Output
#include <stdarg.h>                        // Header File For Variable Argument Routines
#include <gl\gl.h>                        // Header File For The OpenGL32 Library
#include <gl\glu.h>                        // Header File For The GLu32 Library
#include <gl\glaux.h>                // Header File For The Glaux Library

class textPrinter
{
      private:
      GLuint        base;                                // Base Display List For The Font Set
      GLfloat        rot;                                // Used To Rotate The Text
     

      GLYPHMETRICSFLOAT gmf[256];        // Storage For Information About Our Outline Font Characters

      public:
      GLvoid BuildFont(GLvoid);                                                                // Build Our Bitmap Font

      GLvoid KillFont(GLvoid);                                                                        // Delete The Font

      GLvoid glPrint(const char *fmt, ...);                                        // Custom GL "Print" Routine
};

#endif



//Class file for textPrinter
//Note: This code is taken from NeHe tutorial 14: http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=14
#include "textPrinter.h"

GLvoid textPrinter::BuildFont(GLvoid)                                                                // Build Our Bitmap Font
{
        HFONT        font;                                                                                // Windows Font ID

        this->base = glGenLists(256);                                                                // Storage For 256 Characters

        font = CreateFont(        -12,                                                        // Height Of Font
                                                0,                                                                // Width Of Font
                                                0,                                                                // Angle Of Escapement
                                                0,                                                                // Orientation Angle
                                                FW_BOLD,                                                // Font Weight
                                                FALSE,                                                        // Italic
                                                FALSE,                                                        // Underline
                                                FALSE,                                                        // Strikeout
                                                ANSI_CHARSET,                                        // Character Set Identifier
                                                OUT_TT_PRECIS,                                        // Output Precision
                                                CLIP_DEFAULT_PRECIS,                        // Clipping Precision
                                                ANTIALIASED_QUALITY,                        // Output Quality
                                                FF_DONTCARE|DEFAULT_PITCH,                // Family And Pitch
                                                "Comic Sans MS");                                // Font Name

        SelectObject(wglGetCurrentDC(), font);                                                        // Selects The Font We Created

        wglUseFontOutlines(        wglGetCurrentDC(),                                                        // Select The Current DC
                                                0,                                                                // Starting Character
                                                255,                                                        // Number Of Display Lists To Build
                                                this->base,                                                        // Starting Display Lists
                                                0.0f,                                                        // Deviation From The True Outlines
                                                0.2f,                                                        // Font Thickness In The Z Direction
                                                WGL_FONT_POLYGONS,                                // Use Polygons, Not Lines
                                                gmf);                                                        // Address Of Buffer To Recieve Data
}

GLvoid textPrinter::KillFont(GLvoid)                                                                        // Delete The Font
{
  glDeleteLists(this->base, 256);                                                                // Delete All 256 Characters
}

GLvoid textPrinter::glPrint(const char *fmt, ...)                                        // Custom GL "Print" Routine
{
        float                length=0;                                                                // Used To Find The Length Of The Text
        char                text[256];                                                                // Holds Our String
        va_list                ap;                                                                                // Pointer To List Of Arguments

        if (fmt == NULL)                                                                        // If There's No Text
                return;                                                                                        // Do Nothing

        va_start(ap, fmt);                                                                        // Parses The String For Variables
            vsprintf(text, fmt, ap);                                                // And Converts Symbols To Actual Numbers
        va_end(ap);                                                                                        // Results Are Stored In Text

        for (unsigned int loop=0;loop<(strlen(text));loop++)        // Loop To Find Text Length
        {
                length+=gmf[text[loop]].gmfCellIncX;                        // Increase Length By Each Characters Width
        }

        glTranslatef(-length/2,0.0f,0.0f);                                        // Center Our Text On The Screen

        glPushAttrib(GL_LIST_BIT);                                                        // Pushes The Display List Bits
        glListBase(this->base);                                                                        // Sets The Base Character to 0
        glCallLists(strlen(text), GL_UNSIGNED_BYTE, text);        // Draws The Display List Text
        glPopAttrib();                                                                                // Pops The Display List Bits
}

Converting linked list class to template class

by sid78669 at 03:30 AM, 03/09/2010

I have the following classes, SLList, an integer datatype-based linked list and DLList, a template-based linked list. My problem is that SLList is working perfectly, but as soon as i modify it to be used as a template, i get errors, more specifically LNK 2019, i.e. linking errors. I avoided the use of pointers and have been up all night trying to fix it. Please help:

SLList.h:
#ifndef SLLIST_H
#define SLLIST_H

#include <iostream>

using namespace std;

class ListNode
{
public:
        int data;
        ListNode *next;
        ListNode *previous;
        ListNode(){next = previous = NULL;}
        ListNode(int d, ListNode *p = NULL, ListNode *n = NULL)
        {
                data = d;
                previous = p;
                next = n;
        }
};

class SLList
{
private:
        ListNode *head, *tail;
        int length;
public:
        SLList();
        ~SLList();
        bool isEmpty();
        bool isInlist(int data);
        void addToHead(int data);
        void addToTail(int data);
        int removeTail();
        int removeHead();
        bool deleteData(int data);
        void clearList();
        friend ostream &operator<<(ostream &os, SLList& list);
};

#endif

SLList.cpp:
#include "SLList.h"

using namespace std;


SLList::SLList()
{
        tail = head = NULL;
}


SLList::~SLList()
{
        while(!isEmpty())
                removeTail();
}


bool SLList::isEmpty()
{
        if(this->head == NULL)
                return true;
        else
                return false;
        //return (head == NULL) ? true : false;
}


bool SLList::isInlist(int data)
{
        ListNode *temp = head;

        while(temp != NULL && temp->data != data)
                temp = temp->next;

        return (temp == NULL) ? false : true;
}


void SLList::addToHead(int data)
{
        head = new ListNode(data, NULL, head);
       
        if(tail == NULL)
                tail = head;
        else
                head->next->previous = head;
}


void SLList::addToTail(int data)
{
        if(isEmpty())
                head = tail = new ListNode(data);
        else{
                tail->next = new ListNode(data, tail);
                tail->next->previous = tail;
                tail = tail->next;
        }
}


int SLList::removeHead(){
        if(!isEmpty())
        {
                ListNode *temp = head;
                int tempData = temp->data;

                if(head == tail)
                        head = tail = NULL;
                else {
                        head = head->next;
                        head->previous = NULL;
                }

                delete temp;
                return tempData;
        } else
                exit(1);
}


int SLList::removeTail(){
        if(!isEmpty()){
                int tempData = tail->data;

                if(tail != head){
                        ListNode *temp = tail;
                        tail = tail->previous;
                        tail->next = NULL;
                        delete temp;
                } else {
                        delete tail;
                        head = tail = NULL;
                }
                return tempData;
        } else
                exit(1);
}


bool SLList::deleteData(int data)
{
        ListNode *temp = head;

        while(temp != NULL && temp->data != data)
                temp = temp->next;

        if(temp == NULL)
                return false;
        else{
                temp->previous->next = temp->next;
                temp->next->previous = temp->previous;
                delete temp;
                return true;
        }
}


void SLList::clearList(){
        while(!isEmpty())
                removeTail();
}


ostream& operator<<(ostream &os, SLList& l)
{
        if(!l.isEmpty())
        {
                ListNode *temp = l.head;
                for(int i = 1; temp != NULL; i++)
                {
                        os << i << ".\t" << temp->data << endl;
                        temp = temp->next;
                }
        } else
                os << "No data in list." << endl;

        return os;
}

DLList.h:
#ifndef DLLIST_H
#define DLLIST_H

#include <iostream>

using namespace std;

template <class T>
class ListNode
{
        T data;
        ListNode *next;
        ListNode *previous;
        ListNode(){next = previous = NULL;}
        ListNode(T d, ListNode *p = NULL, ListNode *n = NULL)
        {
                data = d;
                previous = p;
                next = n;
        }
};

template <class T>
class DLList
{
private:
        ListNode<T> *head, *tail;
        int length;
public:
        DLList();
        ~DLList();
        bool isEmpty();
        bool isInlist(T data);
        void addToHead(T data);
        void addToTail(T data);
        T removeTail();
        T removeHead();
        bool deleteData(T data);
        void clearList();
        friend ostream &operator<<(ostream &os, DLList<T>& list);
};

#endif

DLList.cpp:
#include "DLList.h"

using namespace std;

template <class T>
DLList<T>::DLList()
{
        tail = head = NULL;
}

template <class T>
DLList<T>::~DLList()
{
        while(!isEmpty())
                removeTail();
}

template <class T>
bool DLList<T>::isEmpty()
{
        if(this->head == NULL)
                return true;
        else
                return false;
}

template <class T>
bool DLList<T>::isInlist(T data)
{
        ListNode<T> *temp = head;

        while(temp != NULL && temp->data != data)
                temp = temp->next;

        if(temp == NULL)
                return false;
        else
                return true;
}

template <class T>
void DLList<T>::addToHead(T data)
{
        head = new ListNode<T>(data, NULL, head);

        if(tail == NULL)
                tail = head;
        else
                head->next->previous = head;
}

template <class T>
void DLList<T>::addToTail(T data)
{
        if(isEmpty())
                head = tail = new ListNode<T>(data);
        else{
                tail->next = new ListNode<T>(data, tail);
                tail->next->previous = tail;
                tail = tail->next;
        }
}

template <class T>
T DLList<T>::removeHead(){
        if(!isEmpty())
        {
                ListNode<T> *temp = head;
                T tempData = temp->data;

                if(head == tail)
                        head = tail = NULL;
                else {
                        head = head->next;
                        head->previous = NULL;
                }

                delete temp;
                return tempData;
        } else
                exit(1);
}

template <class T>
T DLList<T>::removeTail(){
        if(!isEmpty()){
                T tempData = tail->data;

                if(tail != head){
                        ListNode<T> *temp = tail;
                        tail = tail->previous;
                        tail->next = NULL;
                        delete temp;
                } else {
                        delete tail;
                        head = tail = NULL;
                }
                return tempData;
        } else
                exit(1);
}

template <class T>
bool DLList<T>::deleteData(T data)
{
        ListNode<T> *temp = head;

        while(temp != NULL && temp->data != data)
                temp = temp->next;

        if(temp == NULL)
                return false;
        else{
                temp->previous->next = temp->next;
                temp->next->previous = temp->previous;
                delete temp;
                return true;
        }
}

template <class T>
void DLList<T>::clearList(){
        while(!isEmpty())
                removeTail();
}

template <class T>
ostream& operator<<(ostream &os, DLList<T>& l)
{
        if(!l.isEmpty())
        {
                ListNode<T> *temp = l.head;
                for(int i = 1; temp != NULL; i++)
                {
                        os << i << ".\t" << temp->data << endl;
                        temp = temp->next;
                }
        } else
                os << "No data in list." << endl;

        return os;
}

app.cpp
#include "DLList.h" //replace with SLList

using namespace std;

int main()
{
        typedef DLList<int> List; //replace with typedef SLList List;
        List intList;
        intList.addToHead(1);
        intList.addToHead(3);
        intList.addToHead(7);
        intList.addToHead(9);
        intList.addToHead(11);
        intList.addToHead(4);
        intList.addToHead(12);
        intList.addToHead(54);
        intList.addToHead(67);
        intList.deleteData(3);

        cout << intList;
        return 0;       
}

the exact errors is 'Error 1 error LNK2019: unresolved external symbol' for every function declared in main.

create calculator by c++ builder

by alhafes at 01:52 AM, 03/09/2010

Hi everybody
please I want the way to create calculator by c++ builder by using the properties ( Graphical User Interfaces)

Khalid

good c++ books

by alexRivera at 01:51 AM, 03/09/2010

i'm currently taking c++ courses in my college and have been noticing that i'm having trouble grasping the fundamentals of programming or even understanding the concepts that are being taught. the courses are taught with no textbook whatsoever so going back for references leaves me with my lecture notes and the internet which can be confusing. so i just wanted to know what books have been helpful to you in understanding c++.

having trouble merging two sorted arrays.

by alexRivera at 01:42 AM, 03/09/2010

i've been having trouble just figuring out the merging part of the code.

here's the main. everything works except for the merge part that is at the end of the code.
main()
{
      HeapSort heap1;
      HeapSort heap2;
      int one, two;
     
      int x = 0;
     
      int number1,number2;
     
      cout<< " Enter 10 numbers : " << endl;
     
     
      while( x < 10)
      {
           
            cin>>number1;
            heap1.store(number1,x);
            x++;
           
           
      }
     
      cout << endl;
      heap1.sort();
      heap1.printHeap();
     
      x = 0;
      cout<<" now enter 10 more numbers: " << endl;
     
      while( x < 10 )
      {
             
              cin>>number2;
              heap2.store(number2,x);
              x++;
             
      }
     
      heap2.sort();
      heap2.printHeap();
     
// here's the part where i'm having trouble.
  // these are references for number1 and number2
  one = 0;
  two = 0;
      while( one < SIZE && two < SIZE )
      {
             
             
             
              a = heap1.returnvalue(one);
              b = heap2.returnvalue(two);
     
             
            if( a <= b)
            {
               
                a++;
               
              }
             
              else
              {
                  cout<< b << endl;
                  b ++;
              }
         
             
        }
        while( a < heap1.value (one))
        {
               
                a++;
        }
       
        while( b <heap2.value(two))
        {
               
                b++;
        }
      system("pause");
      return 0;

}

Run OS Command in Windows

by ehsun7b at 01:29 AM, 03/09/2010

Hi
I'm using NetBeans + GCC in Linux and also NetBeans + MinGW in Windows.

I need to run an OS Command e.g.:
java -jar myjar.jar

I prefer not to have the terminal/cmd window. It works fine in Linux, but in windows, it ends up in opening a cmd window anyway.

I tried javaw too.

Any help would be appreciated.

Mafia - Party Game

by calypso8 at 23:19 PM, 03/08/2010

Hi, I am fairly new to C++ but love to learn, so I wanted to create a simple program base on the group-party game mafia A.K.A "werewolf."

Just so whoever is not familiar gets the background. I will use just an example of 10 players. In a ten player game, there consists of 4 roles and this is how many there will be in the game:

3 Mafia
1 Cop
1 Doctor
5 Innocent

I figured I would assign those roles "randomly" to each player using those limits. So

0= mafia, 1= cop, 2= doctor, and 3 = innocent

I got somewhat of the code running ok only when generating a 3 player game. I only know how to use a bunch of "IF's" statement, if anyone knows how to make things easier, please feel free to teach me. When I try to compile a 10 player game, after getting all the player's names, the program just goes to a blank new line and nothing happens.
int main()
{
  int numOfPlayers = getNumOfPlayers();
  char playerName[numOfPlayers][256];

  //getPlayerName(numOfPlayers, playerName);
  getPlayerName(numOfPlayers, playerName);

  int player[10];

  //assign the roles to the players
  assignRoles(numOfPlayers, player);

  return 0;
}

int getNumOfPlayers()
{
  int numOfPlayers;
  cout << "How many players are there? ";
  cin >> numOfPlayers;

  return numOfPlayers;
}

char getPlayerName(int numOfPlayers, char playerName[][256])
{
  for(int count = 0; count < numOfPlayers; count++)
    {
      cout << "Please enter the players name: ";
      cin >> playerName[count];
    }
}

int assignRoles(int numOfPlayers, int player[])
{
  int mafia = 0;
  int cop = 0;
  int doc = 0;
  int innocent = 0;

  srand ( time(NULL) );

  for (int i = 0; i < numOfPlayers; i++)
        {
        if (mafia < 3 && cop < 1 && doc < 1)
          {player[i] = rand() % 4;

        switch(player[i])
              {
              case 0:
              mafia++;
              break;

              case 1:
              cop++;
              break;

              case 2:
              doc++;
              break;

              case 3:
              innocent++;
              }
          }
        else    if (mafia < 3 && cop == 1 && doc < 1)
    {
            do (player[i] = rand() % 4);
            while(player[i] != 1);

        switch(player[i])
              {
              case 1:
              mafia++;
              break;

              case 2:
              cop++;
              break;

              case 3:
              doc++;
              break;

              case 4:
              innocent++;
              }
          }
 else  if (mafia < 3 && cop < 1 && doc ==  1 )
          {
            do (player[i] = rand() % 4);
            while(player[i] != 2);

        switch(player[i])
              {
              case 1:
              mafia++;
              break;

              case 2:
              cop++;
              break;

              case 3:
              doc++;
              break;

              case 4:
              innocent++;
            }
          }

  else  if (mafia == 3 && cop < 1 && doc < 1 )
          {
            do (player[i] = rand() % 4);
            while(player[i] != 0);

        switch(player[i])
              {
              case 1:
              mafia++;
              break;

              case 2:
              cop++;
              break;

              case 3:
              doc++;
              break;
              case 4:
              innocent++;
              }
          }

  else  if (mafia == 3 && cop == 1 && doc < 1)
          {
            do (player[i] = rand() % 4);
            while((player[i] != 0) || (player[i] != 1));

        switch(player[i])
              {
              case 1:
              mafia++;
              break;

              case 2:
              cop++;
              break;

              case 3:
              doc++;
            break;

              case 4:
              innocent++;
              }
          }

  else  if (mafia == 3 && cop < 1 && doc == 1 )
          {
            do (player[i] = rand() % 4);
            while((player[i] !=0) || (player[i] != 2));

        switch(player[i])
              {
              case 1:
              mafia++;
              break;

              case 2:
              cop++;
              break;
            case 3:
              doc++;
              break;

              case 4:
              innocent++;
              }
          }

  else  if (mafia < 3 && cop == 1 && doc == 1)
          {
            do (player[i] = rand() % 4);
            while((player[i] != 1) || (player[i] != 2));

        switch(player[i])
              {
              case 1:
              mafia++;
              break;

              case 2:
              cop++;
            break;

              case 3:
              doc++;
              break;

              case 4:
              innocent++;
              }
          }
        }

  cout << "There are " << mafia << " mafias" << endl;
  cout << "There are " << cop << " cops" << endl;
  cout << "There are " << doc << " doctors" << endl;
  cout << "There are " << innocent << " innocent" << endl;

  return 0;
}


So basically, playerName[0] will be player[0],
playerName[1] will be player[1],

Oh, This user will be playing this as playerName[0], and the rest of the players will be computers.

The game continues in 2 Phases, a NIGHT time, and a DAY time.

During the NIGHT time, the mafia's will choose first who do they want to "kill, or get rid of" How should I write it that the mafia's will know who each other is, and if all the mafias are computers, they will randomly choose a person to kill other than mafias. If there is a 1 to 1 ness where more people are chosen, then it loops until there is a majority vote. They can only kill 1 per NIGHT time. The Cop then gets to choose who to investigate and find out their ROLES, this knowledge comes in handy. The Doctor, gets to choose who does he want to heal, which will negate the kill of a mafia if the same person gets chosen.

DAY TIME:
The revealed person whom the Mafia choose is announced dead.
Everyone Gets to vote who they think is the mafia. Of course mafias won't vote for mafias, and the COP will know who is innocent so he won't vote for that person. These votes will all be randomized unless stated above.
Then display who each person voted for.
Whoever gets the most vote, gets killed, reveal their role.
Show how many players are left, and what roles.

REPEAT NIGHT and DAY
Until All Mafias are killed, OR the # of Mafia's are equal to # of The others combine.


Whew, that was long, So, is this writable?? Or is it too much?
Thanks for any help!

about continue keyword and ternary operator.

by malinik at 23:17 PM, 03/08/2010

Hi,
Hope the stated 2 snippets are logically same.
But I am getting error for the second code snippet.

Generally the ternary operator statement is similar to a if else statement.

regarding the second code snippet, where by the continue keyword is used in the ternary opertor statement. It throws the C2059 error.

Why so ?
Please correct me if I am wrong.
Comments and guidance are welcome.

Thanks & Regards,
malini.k
code  snippet 1

Int I =0;
While ( i<7)
{
    I++;
    If (I %2 == 0)
    {
                Continue;
    }
    else
    {
              Cout << I << endl;
    }
}
 
Output: 1 3 5 7.


code snippet 2

int i = 0;

While ( I < 7)
{
  I ++;
  (I %2 == 0) ? continue : cout << i<< endl;
}

Axiomatic Semantics

by easyb at 23:10 PM, 03/08/2010

Dear Colleagues,
Based on the concept of axiomatic semantics (stacks in particular), consider the expression below:
pop(pop(push(4, pop(push(top(push(6,s)), pop(push(7, createstack())))))))
How can this be simplified for ease of understanding.
Thanks

Managing network connection - Idea?

by evstevemd at 22:42 PM, 03/08/2010

Hi,
I need to make application that will act as server and have clients. computers with client will get permission to go to internet or not via server. Only permission to go but they will connect directly on net (not a firewall). Its some sort of internet cafe management depending on time. Once time is out, server should send "sign" to client which will block the internet connection.

I want it to be un-terminable via task manager. So any ideas on where to start?
Thanks :)

C++ triangle help

by bbrradd at 22:34 PM, 03/08/2010

heres my code. i need a triangle that looks like:

****
_ ***
__**
___*

but mine looks like:

****
***
**
*

can anyone help ?

void drawTriangle(){                  //function to hold triangle code

  char c;                            //variable to hold character to make triangle
  int height;                        //variable to hold height of triangle

  cin >> height;
  cin >> c;
  cout<< "Triangle" <<endl;
  for (int i=1;i<=height;i++){
  for (int j=height;j>=1;j--){

      if (i<j){
        cout << c;
      }
      else{cout << " ";}
}
  cout << endl;
  }
}

trouble skipping spaces when reading in file

by jigglymig1 at 22:34 PM, 03/08/2010

Right now i am having difficulty skipping the blank lines in the txt file i read in. I read in all the material i need, but the blank lines come in too and messes up my array.

this is my txt file
####
#M##
#..#
##.#
#..#
####

0

S
E
S
W

0

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

int main()
{
        ifstream dataFile;
        dataFile.open("mice.txt");

        char maze[10][10];
        //char direction[10][1];
        int i=0;
        int j=0;
        char output;

        dataFile.get(output);
        while(output != '0')
        {
                if(output != '0' && output != '\n')
                {
                        maze[i][j] = output;
                        cout << maze[i][j] << endl;
                        j++;
                }
                else
                {
                        maze[i][j] = NULL;
                        i++;
                        j=0;
                }
                //if(output == 'E' || output == 'S' || output == 'W' || output == 'N')
                //{
                //        direction[m][n] = output;
                //        m++;
                //}
                dataFile.get(output);
        }

        for(int m=0; m<(i-1); m++)
        {
                for(int n=0; n<4; n++)
                {
                        cout << maze[m][n];
                }
                cout << endl << endl;
        }
       



        dataFile.close();

        return 0;
}

Debt/Interest Problem

by missmedude at 22:26 PM, 03/08/2010

I just did this and I am not sure I am doing this correctly.

You have purchased a stereo system that cost $1000 on the following credit plan: no payment down, an interest of 18% per year, and monthly payments of $50. The monthly payment of $50 is used to pay the interest and whatever is left is used to pay part of the remaining debt. Hence, the first month you pay 1.5% of $1000 in interest. That is $15 in interest. So, the remaining $35 is deducted from your debt, which leaves you with a debt of $965.00. And its asking for total payment and total interest.

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

main()
{
  cout.setf(ios::fixed);
  cout.setf(ios::showpoint);
  cout.precision(2);

  double cost = 1000, annualInterestRate = 0.18, monthlyPayment = 50, monthlyRate, monthlyInterestRate;
  double monthlyInterest, towardsPrinciple, payment, totalPayment=0, totalInterest;

  while (cost > 0)
  {
      monthlyInterestRate = annualInterestRate / 12;
      monthlyInterest = cost * monthlyInterestRate;
      towardsPrinciple = monthlyPayment - monthlyInterest;
      cost = cost - towardsPrinciple;
      totalInterest = totalInterest + monthlyInterest;
      totalPayment = totalPayment + towardsPrinciple + monthlyInterest;

      if (cost + monthlyInterest >= monthlyPayment)
              payment = monthlyPayment;
      else
              payment = cost + monthlyInterest;

  }

  cout << "The total payment is " << totalPayment << endl;
  cout << "The total interest is " << totalInterest << endl;
 
  getch();
}
Thanks

Convert MPH to Minutes Seconds Per Hour

by missmedude at 22:18 PM, 03/08/2010

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

main()
{
  int spm, mph;
        double spmRemainder, minInHour = 60, secInHour = 3600;

  cout << "Please enter the speed  in miles per hour: ";
  cin >> mph;

  spm = secInHour / mph;
  spmRemainder = secInHour / mph;

  cout << "The speed of in minutes and seconds per mile is: " << spm << " minutes and " ;
  cout << spmRemainder << "seconds.";

  getch();
}
I have having trouble with this problem. Can you guys advise? I am not sure I am doing this right but this is what I have now. I searched around there was one using while loop. I am not sure if its necessary. I am using Borland btw. Thanks in advance

How does IP-Meesenger work?

by InnocentVamp at 20:29 PM, 03/08/2010

Hey friends,

I want to know how does the IP Messenger work? How does it detect all the available online users?

I searched on the web but due to Cyberoam restriction, I am left with very few options. I go by IP Addresses too, but even then I am not getting the desired information.

So can any one please state here how it works?

Thanx in advance...

Find implied Yield not yielding right answer

by riotburn at 20:09 PM, 03/08/2010

I am trying to find the yield of a bond given the bond price, coupon, and semiannual three yr bond using newtons method. The value for B in the output should about equal 101. I have checked everywhere for errors but cant find any. Any ideas?
And yes I am aware about my vectors but dont make fun, i dont know how to automate them.

// bondyield.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>

using namespace std;

double b_est(double x);
double f_deriv(double y);

int _tmain(int argc, _TCHAR* argv[])
{
        double B = 101.0;
        double n = 6.0;

        vector<double> t_cash_flow;
        double arrayOne[]={0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
        t_cash_flow.assign(arrayOne, arrayOne+6);

        vector<double> v_cash_flow;
        double arrayTwo[]={2, 2, 2, 2, 2, 102};
        v_cash_flow.assign(arrayTwo, arrayTwo+6);

        double tol = 10E-6;
        double x0 = 0.03;
        double xnew = x0;
        double xold = x0 - 1.0;
       
        while(abs(xnew - xold) > tol)
        {
                xold = xnew;               
                xnew = xnew + ((b_est(xold) - B)/f_deriv(xold));
        }
        cout << setprecision (12) << xnew << endl;
        double Bp = 0.0;
        double D = 0.0;
        double C = 0.0;
        double disc[6];
        for(int i=0; i<n; ++i)
        {
                disc[i] = exp(-t_cash_flow[i]*xnew);
                Bp = Bp + v_cash_flow[i]*disc[i];
                D = D + t_cash_flow[i]*v_cash_flow[i]*disc[i];
                C = C + pow(t_cash_flow[i], 2)*v_cash_flow[i]*disc[i];
        }
        D = D/Bp;
        C = C/Bp;
       
        cout << setprecision (16) << "Bond Price= " << Bp << endl;
        cout << setprecision (16) << "Duration= " << D << endl;
        cout << setprecision (16) << "Convexity= " << C << endl << endl;


        system ("pause");

        return 0;
}

double b_est(double x)
{       
        double n = 6.0;

        vector<double> t_cash_flow;
        double arrayOne[]={0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
        t_cash_flow.assign(arrayOne, arrayOne+6);

        vector<double> v_cash_flow;
        double arrayTwo[]={2, 2, 2, 2, 2, 102};
        v_cash_flow.assign(arrayTwo, arrayTwo+6);

        double best;
        for(int i=0; i<n; ++i)
                {
                        best = v_cash_flow[i]*exp(-x*t_cash_flow[i]);
                }
        return best;
}

double f_deriv(double y)
{
        double n = 6.0;

        vector<double> t_cash_flow;
        double arrayOne[]={0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
        t_cash_flow.assign(arrayOne, arrayOne+6);

        vector<double> v_cash_flow;
        double arrayTwo[]={2, 2, 2, 2, 2, 102};
        v_cash_flow.assign(arrayTwo, arrayTwo+6);

        double fderiv;
        for(int i=0; i<n; ++i)
                {
                        fderiv = t_cash_flow[i]*v_cash_flow[i]*exp(-y*t_cash_flow[i]);
                }
        return fderiv;
}

C++ please help

by ETP at 19:36 PM, 03/08/2010

Rational fractions are of the form a/b, where a and b are integers and b≠0. Suppose a / b and c / d are fractions. Arithmetic operations on fractions are defined by the following rules:
a/b + c/d = (ad + bc) / bd
a/b – c/d = (ad – bc) / bd
a/b x c/d = (ac)/(bd)
(a/b) / (c/d) = ad/bc, where c/d ≠0
Fractions are compared as follows:
a/b op c/d if ad op bc, where op is any of the relational operators. For example, a/b < c/d if ad < bc.
Design a class, FractionType, that performs the arithmetic and relational operations on fractions. Overload the arithmetic and relational operators so that the appropriate symbols can be used to perform the operation. Also, overload the stream insertion operator and stream extraction operator for easy input and output.
Write a C++ program that uses the FractionType class to perform operations on fractions. Note that your answers do not need to be in lowest terms.

Trouble with array of 5 objects

by sid78669 at 18:41 PM, 03/08/2010

I am trying to compile a code that utilises an array of 5 'hotel' objects as below:
#include "Hotel.h"

using namespace std;

int main()
{
        Hotel *hotels = new Hotel[5];

        hotels[0] = new Hotel("Hershey");
        hotels[1] = new Hotel("Milton");
        hotels[2] = new Hotel("Sheraton");
        hotels[3] = new Hotel("BestWestern");
        hotels[4] = new Hotel("DaysInn");

        for(int i = 0; i < 5; i++)
                hotels[i].print();

        return 0;       
}

Hotel.h:
#ifndef HOTEL_H
#define HOTEL_H

#include "DLList.h"
#include <string>

using namespace std;

class Hotel
{
private:
        char *name;
        DLList<char *> *guestList;
        int guestCount;
       
public:
        Hotel();
        Hotel(char *n);
        ~Hotel();
        char * getName(){return name;}
        DLList<char *> * getGuestList(){return guestList;}
        void checkIn(char *guestName);
        bool checkOut(char *guestName);
        int count(){return guestCount;}
        void print();
};

#endif

My problem is that on compilation I get the following:
Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 11
Error 2 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 12
Error 3 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 13
Error 4 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 14
Error 5 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 15

any suggestions?
I have inlcuded all the code i have on it. Sorry, haven't commented it but is simple enough for any one with intermediate knowledge of c++ to figure out, my appologies in advance :p

Attached Files
File Type: cpp App.cpp (516 Bytes)
File Type: cpp DLList.cpp (2.1 KB)
File Type: h DLList.h (704 Bytes)
File Type: cpp Hotel.cpp (708 Bytes)
File Type: h Hotel.h (457 Bytes)

How to skip integers in C++ taken from a fstream txt file?

by elainadani at 18:25 PM, 03/08/2010

I need to create a function that uses a loop.
This function will open a text file and then must be able to skip a variable number of leading random integers. The program must be able to handle any number of leading random integers.
Example if the opened file reads this on its first line:
100 120 92 82 38 49 102
and the SKIP_NUMBER variable is assigned 3 the number the function would grab is 82.

The function must continue to grab the integers every SKIP_NUMBER until it reaches the end of the file.
These integers taken from the txt file are then placed into another text file.

Please help I'm really lost on how to create this loop! :D

Here is my finction so far...
________________________________________-
//Function skips variables and returns needed integer
int skipVariable (int SKIP_NUMBER)
{

return 0; //temporary return
}
____________________________________
These are my program variables:

// initalize function/variables

ifstream fin;
string IN_FILE_NAME, OUT_FILE_NAME;
int SKIP_NUMBER;

Vector of pointers to objects and their functions

by sblass92 at 16:52 PM, 03/08/2010

Hi,
I'm trying to create a vector array that contains pointers, and these pointers point to objects(particles) that have been created while the program is running.

How do I use the appropriate de-reference operator to use functions of the class particle?
ex. particle.move();
Here is what I have and my guess:

#include <vector>
#include <particle.h>

void main() {
vector <particle*> vect_a;

vect_a.push_back(new particle);

*(vect_a[0]).move();

}

Here, the compiler doesn't think i've declared 'move', but particle.move() works fine outside of the vector of pointers.

-Thanks

Modifying strings from input file to output file

by blakenbama at 16:52 PM, 03/08/2010

Hello everyone,

I need help. In my assignment i have an input file that contains string data: ----> i love music and chicken. today is the first day of the rest of your life. my name is john.

I must change it to the following in the output file: ----> I love music and chicken. Today is the first day of the rest of your life. My name is john.

I need to use this function to help achieve this:
void initialCap(string&);


No classes are required.

All the white space is erased initially that's why i use the insert function. However, the last word "john" is erased when i use this function. How do i increase the size of the string in order to still have john included in the output. I realize string is an array and arrays are immutable but i know there has to be a way around this. Also, I can't capitalize the words i need to capitalize. I need to use the replace function but, i'm not sure how the parameters work.

Any help is greatly appreciated

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


void initialCap(string&);

int main () {       
        ifstream inputFile;       
        inputFile.open("C:/Notepad++/input.txt");
        ofstream outputFile;       
        outputFile.open("c:/Notepad++/output.txt");
       
        string baseSentence = "";
        string str2 = " dave";
       
       

        if (inputFile) {
                        while (!inputFile.eof()) {       
                                string str1 = baseSentence;
                                str1.insert(0," ");
                                inputFile>>baseSentence;
                                cout<<str1;       
                                outputFile<<baseSentence;       
                }               
               
        }
        else {
                cout<<"this file does not exist dave!";
        }       

        inputFile.close();
        outputFile.close();
        cout << "\n\n";
        system("pause");
        return 0;
}

file trouble

by smeghead007 at 15:24 PM, 03/08/2010

Ok what im tryin to do is open a file by the name a user request after that i ask the user and id number to look for in the file if its found i want to display it along with the name after it but i cant figure out how to get it to display the name and id num if its not found then gives the user the option to add it to the file and then look again for another id num..... please help


/*************************************************************************************
** File name        : lab6_driver.cpp
**
** This program will open and read a file then ask user for an ID to look up and then display if its found or not.
**
**
**
** Programmer        : Christopher Erb
**
** Date Created        : 02/26/10
**
** Date last revised:
************************************************************************************/

#include <iostream>                                    // Need for cout,cin
#include<iomanip>                  // Need setf,fixed,showpoint,setprecision
#include <stdio.h>                                    // Need for getchar
#include <fstream>                                        // Needed for files
#include <cstdlib>                                        // Needed for exit function
#include <string>                                        // Need for string class

using namespace std;


string getInputFileName(); // a function to prompt for the complete file name
int getId(); // Function that gets the id number
void search(ofstream& outFile, ifstream& inFile, int);

int main ()
{


        ofstream outFile;
        ifstream inFile;
        string fileName; // complete file name including the path

        fileName = getInputFileName(); // prompt and obtain the full file name

        // try to open the file
        outFile.open(fileName.c_str(),ios::in | ios::out | ios::app);
        inFile.open(fileName.c_str(),ios::in);

        if (!inFile.is_open())
        {
                cerr << "File open error " ;
                cout << " Press enter to continue" << endl;
                cin.ignore();
                char ch = getchar();
                exit (1);
        }

        if(!outFile.is_open())
        {
                cerr << "File open Error Creating file" ;
                cout << " Press enter to continue" << endl;
                cin.ignore();
                char ch = getchar();
                exit(1);
        }



        /*
        char c;
        inFile.get (c);
        while (!inFile.eof ())
        {
        cout << c;
        inFile.get (c);
        }
        string str;
        int id_num;
        while (inFile >> str >> id_num)
        { cout << str <<  "ID" << id_num << endl;
        }
        */
        int ID;
        ID = getId();
        search(outFile, inFile, ID);
        outFile.close();
        inFile.close();
        cout.setf (ios::showpoint );
        cout.setf( ios::fixed);
        cout << setprecision(2);

        cout << " Press Enter to continue" << endl;
        cin.ignore();
        char ch = getchar();

        return 0;

}

//************************************************************
//
// Function name: getInputFileName
//
// Purpose: to prompt for the fully qualified name of a file
//              i.e. including the path of the file
//
// Input parameters: none
//
// Output parameters: none
//
// Return Value: a string containing the fully qualified name
//              of a file
//
//************************************************************

string getInputFileName()
{
        string f_Name; // fully qualified name of the file

        cout << "Please enter the fully qualified name of the " << endl
                << "input text file (i.e. including the path): ";
        cin >> f_Name ;
        cout << endl; // skip a line

        return f_Name;
}
//************************************************************
//
// Function name: getId
//
// Purpose: to prompt the user for the ID
//           
//
// Input parameters: char id
//
// Output parameters: none
//
// Return Value: inputId
//             
//
//************************************************************

int getId ()
{
        int inputId;
        cout << " Enter the ID number: " ;
        cin >> inputId ;



        return inputId;
}
//************************************************************
//
// Function name: Search
//
// Purpose: Locate the ID the user entered. If found displays it with the name if not asks to enter into to the file
//           
//
// Input parameters: string id, filehandle passed by reference (ifstream &inFile, ofstream &outFile)
//
// Output parameters: none
//
// Return Value:
//             
//
//************************************************************

void search(ofstream &outFile, ifstream &inFile, int ID)
{
        int id_num;
        string name;
        char userreply;
        char lookagain = 'Y';
        string inputname;
       

        while (!inFile.eof() && (lookagain == 'Y' || lookagain == 'y'))
        {
                inFile.seekg (0, ios::beg);
                inFile.getline(file);
                if ( ID == id_num)
                {
                        std::cout << id_num << name;
                }
                else
                {
                        cout << "Id not found would you like to add it? Y/N " ;
                        cin >> userreply;
                        if( userreply == 'Y' || userreply == 'y')
                        {
                                cout << " What name would you like to input?" ;
                                cin >> inputname;
                                outFile << "\n" << ID << " " << inputname;
                                outFile.flush();

                        }
                }

                cout << "Look for another ID? Y/N " ;
                cin >> lookagain;

                if (lookagain == 'Y' || lookagain == 'y')
                {
                       
                        inFile.clear();
                        int getId ();

                }
                else
                {
                        break;
                }
        }
}

need help with for loop?

by jjmy95 at 15:20 PM, 03/08/2010

I have an array of 20 elements with numbers between 1 and 8. I need a for loop that will give me the number of elements greater than 1???

Hexadecimal help

by loststudent88 at 15:13 PM, 03/08/2010

Hello I am working on a program and have become pretty confused...
I am supposed to write a program that will convert html colours expressed as 6 hexadecimal digits to their individual red, green, and blue components expressed in decimal. If anyone can help me out with some pointers of how to do this then that would be great. Thanks
If you have some DACL permissions on a file, you can use SetFileSecurity() to change the permissions to something else, but what happens when someone deletes all of the DACL? Now you no longer have WRITE_DAC permissions, so you can not modify any discretionary ACE's to it. I have administrative permissions, so how do I restore WRITE_DAC privileges to myself?
Thank you for help :)

Help? Stuck.

by Flow2 at 13:17 PM, 03/08/2010

Now I am on my way to making a little command prompt program where it types out the alphabet and removes the vowels as a test. BUT, here's the thing, no errors nothing but it doesn't work.
Anyway here is the code if anyone can tell me what is wrong :-/

#include <iostream>
#include <string>

using namespace std;

int main( void )
{
    string word1 =  "A";
    string word2 =  "B";
    string word3 =  "C";
    string word4 =  "D";
    string word5 =  "E";
    string word6 =  "F";
    string word7 =  "G";
    string word8 =  "H";
    string word9 =  "I";
    string word10 = "J";
    string word11 = "K";
    string word12 = "L";
    string word13 = "M";
    string word14 = "N";
    string word15 = "O";
    string word16 = "P";
    string word17 = "Q";
    string word18 = "R";
    string word19 = "S";
    string word20 = "T";
    string word21 = "U";
    string word22 = "V";
    string word23 = "W";
    string word24 = "X";
    string word25 = "Y";
    string word26 = "Z";
   
    string phrase = word1 + " " + word2 + " " + word3 + " " + word4 + " " + word5 + " " + word6 + " " + word7 + " " + word8 + " " + word9 + " " + word10 + " " + word11 + " " + word12 + " " + word13 + " " + word14 + " " + word15 + " " + word16 + " " + word17 + " " + word18 + " " + word19 + " " + word20 + " " + word21 + " " + word22 + " " + word23 + " " + word24 + " " + word25 + " " + word26;
    cout << phrase << "\n\n";
    cout << "The alphabet has..." << phrase.size() << " letters in it.\n\n";
 
for (int i = 0; i < phrase.size(); i++)
cout << "The letter at position " << i << " is: " << phrase[i] << endl;


if(phrase.empty())
cout << "\n No more letters.\n";

 return 0;

}

C++ or C course

by megmar at 13:16 PM, 03/08/2010

I am looking to take a course in C++, but is that language popular now, or is everything more C? Please advise.

1o top tips for code porting c/c++.

by tajendra at 12:09 PM, 03/08/2010

Code portability basically refers to making source code able to compile on different platform without making any changes in source code.
While coding its very important to keep portability in mind.The best way to introduce code portability is while coding.Keeping certain things into account we can achieve code portability with lesser effort, which we will discuss in this post.There are certain tools too which detect portability problems on source code, its a post processing of code and requires extra effort.
Non-portable code introduces problems like maintenance of different versions, reduces readability, reduces understanding of code etc...
Efforts needs to make legacy or old source code portable, can really make you feel lost in this big programming ocean. So, the best policy is to keep portability into account while writing code, it saves lots of time and efforts on rework. Big question now is - "How to write portable code?".Our source code should be compatible with different environment like different processor, different OS, different version of libraries etc... In this post we would focus on basic tips need to be kept in mind while writing code.

1) Don't assume data type size to be constant across platform, as it may change with platform.
Many a times programmers makes a common mistake by assuming size of pointer and long same.If in some expression sizeof(long) is used, it may give different result on 32-bit and 64-bit OS version. Like if we talk about Microsoft Visual Studio running on 64-bit OS version the pointer size would be 8 byte and size of long comes out to be 4 byte. Program written with such assumption would give false result or may even get crash.So, one has to be very cautious while using data type size across the platform.

2) Don't use specific system constant.
System specific constant should not be used as they are not portable, we are some time not aware of them also. Like system constant "NULL" is specific to windows and will give compilation error on other platform. Instead of "NULL" one can use "0".

3) System file/folder path notation may vary on different platform.
When working with file path one need to be cautious for example "c:\\TestFile.txt" will work on Windows but give error on Linux.For this one i recommend to use forward slash "c://TestFile.txt" , it would work well on both windows and Linux.

4) Avoid using system specific models/libraries.
Don't use system specific models/libraries like Event handling model, Threading libraries, File Creation libraries etc.. . As they are not compatible across platform. Write a wrapper around such models and within wrapper use generic portable libraries. For example, Windows even handling model is totally different from Linux. Windows have special mode for handling events, like we may not find timed wait for multiple object on other platform.

5) Always write default statement in switch case.
Many latest compiler gives compilation error if default is not specified.

6) Always specify return type for functions.
Many latest compiler gives compilation error if return type is not specified.

7) Always specify type with static variables.
Variables declared with static keyword must contain data type with it, some old compiler take int as default type but modern compiler will generate compilation error for it.

8) Always take care of scope of variable.
Like some compiler support variable scope limited to for() while some compiler dont.
For example:-
Don't prefer writing code as below (Non-portable code).
        {
          for(int i ; ;)
          {
          //do some thing
          }


          for(int i ; ;)
        {
          //do some thing
          }

        }


        Prefer writing code as below (Portable code)
        {
          for(int i ; ;)
          {
          //do some thing
          }

          for(int j ; ;)
        {
          //do some thing
          }

        }
9) Don't use C++ commenting style in C code.
Don't use // commenting style in c code, as compile other then microsoft visual studio may generate error for it. Prefer using /* */ commenting style.

10) Take care of include depth for header files and also for file code size.
Microsoft visual studio compiler generated error like "internal compiler error" if include depth is too large or file size exceeds certain limit. Always take care of file size and include depth.

I have tried to cover 10 basic tips for code portability for beginners though there are several other areas too, where we need to focus on advanced portability issues, for e.g. dealing with classes, virtual functions, exception handling, compiler directives, run-time identification. I will cover this topic separately bye for now.

Hope you enjoyed this post ! <<plug removed>>

Keep Rocking
-Tajendra

payroll program help

by rookanga at 11:13 AM, 03/08/2010

I am having trouble trying to finish this program, What I am suppose to do is make a loop program that should ask the user for the employees number, gross pay, state tax, federal tax, and FICA withholdings. The loop will terminate when 0 is entered for the employee number. After the data is entered, the program should display totals for gross pay, state tax, federal tax, FICA withholdings, and net pay. I can't except any negative number and I can't accept the value of the state, federal, or FICA withholdings to be greater than the gross pay, if it is print the error massage

I know I don't have all of my display totals code in, but what I am having trouble is on the terminating the code if a 0 is entered for the employees number, and I am not suppose to accept any negative number for any of this program. I don't remember how to do it. Can someone please help me out.

# include <iostream>
using namespace std;
int main()
{
        int employee;
        int gross;
        int state;
        int federal;
        int FICA;

        cout << "WEhat is the employees number " << endl;
        cin >> employee;
        for ( employee = 1; employee >=, employee ++)

        cout <<"What is there gross pay" << endl;
        cin >> gross;

        cout << "What is there state tax " << endl;
        cin >> state;

        cout << "What is there federtal tax" << encl;
        cin >> federal;

        cout << "What is there FICA" << endl;
        cin >> FICA;

        if (state + federal + FICA) > gross;
        cout << "YOu are taking to much out of the persons check, please redo" << endl;

cout << " Your employee number is" << employee << endl;

        return 0;
}

Template Functions

by clutchkiller at 09:58 AM, 03/08/2010

Why are you able to declare them using the class keyword or typename keyword? Is there absolutley no difference? Thanks

Need help. Returning an array not working

by Nicky4815 at 09:52 AM, 03/08/2010

Hi all,

I'm doing a 3d pacman game for a university project which has to be written in c++ (3rd year and having never been taught any c++) My problem is that when I initialise the map array I cannot return the value back to the main method.

The values in the arrays are int's which will be used in constructing the maps (e.g 0 = wall 1 = nothing etc.)

When compiling, the line in the "getCell(x,y)" method gives the error which is "'map' undeclared (first use this function)" and if I put "this->map" it gives an "invalid use of 'this' in non-member function"

Any healp would be greatly appreciated.

My mapInit header:
//Header file for the map initialiser
#ifndef MAPINIT_H_
#define MAPINIT_H_

#include <windows.h>                // Header File For Windows
#include <math.h>                        // Header File For Windows Math Library
#include <stdio.h>                        // Header File For Standard Input/Output
#include <stdarg.h>                        // Header File For Variable Argument Routines
#include <gl\gl.h>                        // Header File For The OpenGL32 Library
#include <gl\glu.h>                        // Header File For The GLu32 Library
#include <gl\glaux.h>                // Header File For The Glaux Library


//Class mapInit begin
class mapInit
{
      public:
      unsigned int getCell(unsigned int x, unsigned int y);
      void setMap( unsigned int mapSet );
     
      private:
      unsigned int map[22][19];
};

#endif

My mapInit class:
//Map initialization class

//Code begin

#include "mapInit.h"

void mapInit::setMap( unsigned int mapSet )
{   
    if ( mapSet == 1 )
    {
          unsigned int mapBuffer[22][19] = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                  {0,6,6,6,6,6,9,9,9,9,9,9,6,6,6,6,6,6,0},
                  {0,6,0,0,0,0,0,0,6,0,6,0,0,0,0,0,0,6,0},
                  {0,6,6,8,8,0,6,6,6,0,6,6,6,0,6,6,6,6,0},
                  {0,0,6,0,6,0,6,0,0,0,0,0,6,0,8,0,6,0,0},
                  {0,7,6,0,6,6,6,6,6,2,6,6,6,8,8,0,6,7,0},
                  {0,6,0,0,6,0,0,0,6,0,6,0,0,0,8,0,0,6,0},
                  {0,6,8,8,6,6,6,6,6,0,6,6,6,6,6,6,6,6,0},
                  {0,0,0,0,6,0,1,0,0,0,0,0,1,0,6,0,0,0,0},
                  {0,0,0,0,6,0,1,1,1,12,1,1,1,0,9,0,0,0,0},
                  {0,0,0,0,6,0,1,0,0,0,0,0,1,0,9,0,0,0,0},
                  {1,1,1,1,6,1,1,0,4,3,4,0,1,1,9,1,1,1,1},
                  {0,0,0,0,6,0,1,0,0,5,0,0,1,0,9,0,0,0,0},
                  {0,0,0,0,6,0,1,1,1,1,1,1,1,0,9,0,0,0,0},
                  {0,0,0,0,9,0,0,0,1,0,1,0,0,0,6,0,0,0,0},
                  {0,6,6,6,9,0,6,6,6,0,6,6,6,0,6,6,6,6,0},
                  {0,6,0,0,9,0,6,0,0,0,0,0,6,0,6,0,0,6,0},
                  {0,6,6,6,9,6,6,6,6,8,8,8,6,6,6,6,6,6,0},
                  {0,6,0,0,9,0,0,0,6,0,6,0,0,0,6,0,0,6,0},
                  {0,7,0,0,6,0,0,0,6,0,6,0,0,0,6,0,0,7,0},
                  {0,6,6,6,6,8,8,8,6,0,6,6,6,6,6,6,6,6,0},
                  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} };
                 
                  this->map[22][19] = mapBuffer[22][19];
    }
    else if ( mapSet == 2 )
    {
          unsigned int mapBuffer[22][19] = { {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0},
                  {0,6,6,6,6,6,6,6,0,1,0,6,6,6,6,8,8,6,0},
                  {0,6,0,0,6,0,0,6,0,1,0,6,0,0,6,0,0,6,0},
                  {0,7,0,0,6,6,6,6,0,1,0,6,8,8,6,0,0,7,0},
                  {0,6,0,0,6,0,0,6,6,2,6,6,0,0,6,0,0,8,0},
                  {0,6,6,6,6,6,6,0,6,0,6,0,6,6,6,6,6,6,0},
                  {0,9,0,0,6,0,6,0,6,0,6,0,6,0,6,0,0,8,0},
                  {0,9,0,0,6,0,6,0,6,0,6,0,6,0,6,0,0,6,0},
                  {0,9,6,8,8,8,6,1,1,1,1,1,9,9,9,9,6,8,0},
                  {0,9,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,9,0},
                  {0,9,6,6,0,0,0,4,4,3,4,4,0,0,0,6,6,9,0},
                  {0,9,0,6,8,6,0,0,0,0,0,0,0,6,6,6,0,9,0},
                  {0,6,6,0,0,6,0,10,10,10,10,10,0,9,0,0,6,6,0},
                  {0,0,6,0,0,6,0,10,0,1,0,10,0,9,0,0,6,0,0},
                  {0,6,6,0,0,6,10,10,0,1,0,10,10,9,0,0,6,6,0},
                  {0,6,0,0,6,6,0,0,0,12,0,0,0,6,6,0,0,6,0},
                  {0,6,6,0,6,0,8,6,6,0,6,6,6,0,6,0,6,6,0},
                  {0,0,6,8,6,6,8,0,6,6,6,0,8,6,6,6,6,0,0},
                  {0,6,6,0,6,0,6,6,0,1,0,6,6,0,6,0,6,6,0},
                  {0,6,0,6,6,6,0,6,0,1,0,6,0,6,6,6,0,6,0},
                  {0,7,6,6,0,6,6,6,0,1,0,6,6,6,0,6,6,7,0},
                  {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0} };
                 
                  this->map[22][19] = mapBuffer[22][19];
    }
    else if ( mapSet == 3 )
    {
          unsigned int mapBuffer[22][19] = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                  {0,7,6,6,0,6,6,6,0,6,6,6,0,6,6,6,6,7,0},
                  {1,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,1},
                  {0,6,0,6,0,6,6,6,0,9,0,8,6,6,0,6,0,6,0},
                  {0,6,0,9,0,6,0,6,8,9,0,6,0,8,6,6,0,6,0},
                  {0,6,6,9,6,6,0,6,0,9,6,6,0,6,0,6,6,6,0},
                  {0,6,0,9,0,6,0,6,0,9,0,6,0,8,0,11,0,0,0},
                  {0,6,0,6,0,8,6,6,0,9,0,9,0,6,6,11,5,4,0},
                  {0,6,0,8,6,6,0,6,0,6,2,9,6,6,0,11,0,4,0},
                  {0,6,6,6,0,9,0,6,6,6,0,9,0,6,0,11,0,4,0},
                  {0,6,0,8,0,9,0,6,0,6,0,9,0,6,0,11,5,3,0},
                  {0,6,0,8,0,9,6,6,0,6,0,9,0,6,0,11,0,4,0},
                  {0,6,0,6,0,9,0,6,0,9,0,9,0,6,6,11,0,4,0},
                  {0,8,6,6,0,6,0,6,6,9,6,9,0,6,0,11,5,4,0},
                  {0,8,0,6,6,6,0,6,0,9,0,9,6,6,0,11,0,0,0},
                  {0,8,0,6,0,6,0,6,0,6,0,9,0,6,0,6,6,6,0},
                  {0,8,6,6,0,6,6,6,0,6,0,6,0,6,6,8,0,6,0},
                  {0,6,0,6,0,6,0,10,0,6,6,6,0,6,0,8,0,6,0},
                  {0,6,0,6,6,6,0,10,0,6,0,6,6,6,0,8,0,6,0},
                  {1,6,0,6,0,6,0,10,0,6,0,6,0,6,0,8,0,6,1},
                  {0,7,6,6,0,6,0,12,0,6,6,6,0,6,6,6,6,7,0},
                  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} };
                 
                  this->map[22][19] = mapBuffer[22][19];
    }
    else if ( mapSet == 4 )
    {
          unsigned int mapBuffer[22][19] = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                  {0,7,6,6,6,6,0,4,3,4,0,6,6,6,6,6,6,7,0},
                  {0,6,0,6,0,6,0,0,5,0,0,6,0,6,0,6,0,6,0},
                  {0,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,0},
                  {0,6,0,6,0,8,0,6,0,6,0,6,0,6,0,6,0,6,0},
                  {0,6,6,6,6,6,6,9,9,9,6,6,6,6,6,6,6,6,0},
                  {0,6,0,8,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0},
                  {0,6,6,6,6,6,6,6,2,9,9,9,9,9,6,6,6,6,0},
                  {0,6,0,8,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0},
                  {0,6,6,6,6,6,9,9,9,9,9,9,6,6,6,6,6,6,0},
                  {0,9,0,6,0,8,0,6,0,6,0,8,0,6,0,6,0,6,0},
                  {0,9,6,8,6,6,9,9,9,9,9,9,6,6,6,6,6,6,0},
                  {0,9,0,6,0,6,0,0,0,6,0,6,0,8,0,6,0,6,0},
                  {0,9,6,6,6,6,0,10,10,6,6,6,6,9,6,9,6,9,0},
                  {0,9,0,6,0,6,0,10,0,0,0,0,0,9,0,9,0,9,0},
                  {0,9,6,8,6,6,0,10,10,10,10,12,0,9,6,9,6,9,0},
                  {0,6,0,6,0,6,0,0,0,0,0,0,0,6,0,6,0,9,0},
                  {0,6,6,6,6,6,6,6,8,6,8,8,8,8,6,6,6,6,0},
                  {0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0},
                  {0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0},
                  {0,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,0},
                  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} };
                 
                  this->map[22][19] = mapBuffer[22][19];
    }
    else if ( mapSet == 5 )
    {
         
          unsigned int mapBuffer[22][19] = { {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0},
                  {0,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,0},
                  {0,6,0,0,0,0,0,0,6,0,6,0,0,5,0,0,0,6,0},
                  {0,6,0,12,10,0,6,6,6,0,6,0,4,3,4,4,0,6,0},
                  {0,6,0,0,10,10,6,0,6,0,6,0,0,0,5,0,0,6,0},
                  {0,8,0,0,0,0,6,0,6,0,6,6,6,6,6,6,6,6,0},
                  {0,8,0,6,6,6,6,0,6,0,6,0,0,0,0,0,0,6,0},
                  {0,8,0,6,0,0,0,0,9,0,6,6,6,6,6,6,6,6,0},
                  {0,8,0,6,6,6,6,6,9,0,8,0,8,0,8,0,8,0,0},
                  {0,8,0,0,0,0,0,0,9,0,8,0,8,0,8,0,8,0,0},
                  {0,6,6,6,6,2,6,6,6,0,6,9,9,9,9,9,9,6,0},
                  {0,8,0,0,0,0,0,0,6,0,6,0,0,0,0,0,0,6,0},
                  {0,8,0,6,6,6,6,0,6,0,6,6,6,6,6,6,6,6,0},
                  {0,8,0,6,0,0,9,0,6,0,0,8,0,8,0,8,0,8,0},
                  {0,8,0,6,0,0,9,0,6,0,0,8,0,8,0,8,0,8,0},
                  {0,8,6,6,6,6,9,6,6,0,6,6,6,6,6,6,6,6,0},
                  {0,8,0,6,0,0,9,0,6,0,6,0,0,0,0,0,0,6,0},
                  {0,8,0,6,0,0,9,0,6,0,6,9,9,9,9,9,9,6,0},
                  {0,8,0,6,6,6,6,0,6,0,8,0,8,0,0,8,0,8,0},
                  {0,6,0,0,0,0,0,0,6,0,8,0,8,0,0,8,0,8,0},
                  {0,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,0},
                  {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0} };
                 
                  this->map[22][19] = mapBuffer[22][19];
                 
                 
    }
}

unsigned int getCell(unsigned int x, unsigned int y)
{
        return this->map[x][y];
}

Noob needs help pretty please.

by Candi~ at 09:45 AM, 03/08/2010

Hi everybody, my name is Candi and I am new here, I was lucky enough to find this forum.
I am new to C++ and am teaching myself because I can't afford school at this time, all I can afford is second hand books :( and I am having a serious problems with this question, and was wondering if any of you could please assist me in writing this and understanding this code pretty please :?:

Just so there is no confusion I am attempting to teach myself C++ through secondhand books, and tutorials, the question I ask comes from a book I have begone to read and thought I was doing rather well, the question stopped me dead in my tracks.
I do not go to school because I can't afford it, due to the recession where I live. I hope hope someone can help me please, I am determined to learn on my own. Can anyone suggest good books e-books and video tutorials as well for a beginner?

Here is my problem maybe someone can help me?

The problem is that I want to write an interactive program in C++ whose input is a series of 6 temperatures from the user of the program. It should write out on file tempdata.dat each temperature as well as the difference between the current temperature and the one preceding it. The difference is not output for the first temperature that is input. At the end of the program, the average temperature should be displayed for the user via cout.

For example 34.5 38.6 42.4 46.8 51.3 63.1

The file tempdata.dat would contain
34.5
38.6 4.1
42.4 3.8
46.4 4.4
46.8 4.4
51.3 4.5

Using proper formatting and comments in the code.

Thanks everyone,
Candi~

calculating days in a month

by fugnut at 09:12 AM, 03/08/2010

Hello all,
I am working with a program to calculate the days in a given month. We are to use functions and bool. I have the below code, which worked until I tried to create the function. I continue to get an error about "numberOfDays" not being initialized however if I state that numberOfDays = 0, that is all i get in return, 0....any suggestions?
//C++ program to determin the number of days in a given month
//of a given year.

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int calcDays (int);

int main ()
{
        int month, year;
        int numberOfDays;
               

        cout <<"Month and year, and I will calculate the number of days in that month. ";
        cout <<endl;
        cout <<"Enter the month (eg. 02 for February): ";
        cin >> month;
        cout <<"Enter the year (eg. 2010): ";
        cin >>year;
       
        calcDays (numberOfDays);
       
       
        cout <<"Month    "<<"Year    "<<"# of Days";
        cout <<endl;
        cout << setfill('0') << setw(2)<<month<<"        "<<year<<"        "<<numberOfDays;
        cout <<endl;

       
        system ("pause");
        return 0;
}
int calcDays (int)

{
int month = 0;
int Days;
int year = 0;


if (month == 4 || month == 6 || month == 9 || month == 11)
        Days = 30;       

        else if (month == 02)
        {
                bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
                       
                if (isLeapYear == 0)
                        Days = 29;
                else
                        Days = 28;
        }
                else
                Days = 31;
return Days;
}

Comparing Vectors

by Web_Sailor at 08:28 AM, 03/08/2010

Hi,

I am trying to compare 2 vectors to remove any kind of overlap. I have written a simple program but it gives a segmentation fault once I increase / decrease number of vector elements in both.

Is there a better way of doing this. Especially suppose one of the vector is empty or both are empty my program won't work. Can anybody help.

Here is my program:-

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main(){

          vector<string> v1;
          vector<string> v2;

          v1.push_back("A");
          v1.push_back("B");
          //v1.push_back("C");
          //v1.push_back("D");

          v2.push_back("A");
          v2.push_back("B");
          v2.push_back("C");
          v2.push_back("D");
          //v2.push_back("E");
          //v2.push_back("F");
          //v2.push_back("G");

          vector<string>::iterator iter = v2.begin();

    while( iter != v2.end() )
    {
        for(int i=0; i<v1.size(); i++){
            if (*iter == v1[i]){
                    iter = v2.erase( iter );
            }
            else{
                ++iter;
            }
        }
    }

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

}

In this program output is correct:-

C 
D

but if I increase or decrease elements the problem starts and gives segmentation faults.

Thanks

Help with debugging pointer variable linked list

by atticusr5 at 07:55 AM, 03/08/2010

Hey everyone,

I am using Visual Studio 2008 to debug some code where the goal is create a linked list using pointer variables. Here is the main error I am getting when trying to compile:

error C2227: left of '->Account' must point to class/struct/union/generic type      type is 'Link_t'


If I can figure out what it means, I will be able to get like 98% of the code debugged.

At any rate here is my code, any help would be appreciated because linked lists are giving be a great bit of trouble

//Assignment 8
//Linked Lists
//Pointer Variable Implementation
//Devang Joshi

#include <iostream>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <fstream>
using namespace std;

//************************************************************************************************* 
                                                        /* Global Variables */   
//*************************************************************************************************
 
    const int NAMESIZE=25;
    const int FILENAME=51;
    const int MAXLISTSIZE=200;     
 
    typedef char Name_t[NAMESIZE];
    typedef char Filename_t[FILENAME];
    typedef int ID_t;
    typedef double Bal_t;
    typedef fstream Infile_t;
    typedef fstream Outfile_t;
    typedef int Link_t;     
 
     
//*************************************************************************************************
                                                    /* Class Declerations */ 
//*************************************************************************************************

    class cAccount
    {
                private:
                       
                    Name_t fname;
                      Name_t lname;
                      ID_t aID;
                      Bal_t aBal;     

              public:     

                      cAccount();                     
                      void Read (Infile_t &Infile);   
                      void Print (Outfile_t &Outfile); 
                      void Display();                 
                  int compID2ID(cAccount NewAccount);                       

      };// end cAccount     
//*************************************************************************************************
                                                    /* Struct Declerations */
//*************************************************************************************************
 
      struct LLEle_t
      {
              cAccount Account;
                LLEle_t * Link_t;     

      };// end ListEle_t   
//*************************************************************************************************
                                                  /* Link Decleration */
//*************************************************************************************************

      typedef LLEle_t * Link;     

//*************************************************************************************************
                                          /* Class Function Implementations */     
//*************************************************************************************************
      cAccount::cAccount()
      {
              strcpy(fname,"");
                strcpy(lname,"");                                               
                aID=0;
                aBal=0; 
         
          }// end cAccount::cAccount     
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      void cAccount::Read(Infile_t &Infile)
          { Infile>>aID>>lname>>fname>>aBal;}// end cAccount::Read             
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      void cAccount::Print(Outfile_t &Outfile) 
      {
              Outfile<<setw(10)<<"ACCOUNT-ID: "<<aID<<endl;
                Outfile<<setw(10)<<"ACCOUNT NAME: "<<lname<<","<<fname<<endl;     
                Outfile<<setw(10)<<"ACCOUNT BALANCE: $"<<aBal<<endl;
                Outfile<<"------------------------------------------------"<<endl; 
 
          }// end cAccount::Print         
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      void cAccount::Display()
      {
              cout<<setw(10)<<"ACCOUNT-ID: "<<aID<<endl;
                cout<<setw(10)<<"ACCOUNT NAME: "<<lname<<","<<fname<<endl;       
                cout<<setw(10)<<"ACCOUNT BALANCE: $"<<aBal<<endl;
                cout<<"------------------------------------------------"<<endl;     
 
      }// end cAccount::Display     
 //_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      int cAccount::compID2ID(cAccount NewAccount)
      {
                  int count;
                count=0;     

                if(this->aID > NewAccount.aID)
                { count=-1;}// end if   

              else if(this->aID < NewAccount.aID)     
                { count=1; }// end else if     

                  else
                { count=0;}//end else     

                return count;

      }// end cAccount::compID2ID   
//*************************************************************************************************
                                                        /* Function Prototypes */
//*************************************************************************************************
 
      void Insert(Link_t &Head, Link_t &Pred,cAccount NewAccount);
      void Search4Pred(Link_t &Pred,Link_t List,Link_t Start, cAccount Account); 
      void Add(Link_t &Avail,Link_t &Start, cAccount NewAccount); 
      void Load(Link_t &Start,Link_t &Avail); 
      void Display(Link_t Start, Link_t Avail);
          void Print(Link_t Start,Link_t Avail); 
     
//*************************************************************************************************
                                                                    /* MAIN */     
//*************************************************************************************************

      int main()
      {
                  int COUNT=0;
                Link_t Start=0;
                Link_t Avail=0;
                cAccount Account;
                Infile_t Infile;

          /* FUNCTION CALLS */

                Load(Start,Avail);
                Display(Start,Avail);
                Print(Start,Avail);
               
                return 0;

      }// end main
//*************************************************************************************************
                                                    /* Function Implementations */ 
//*************************************************************************************************
      void Insert(Link_t &Head, Link_t &Pred,cAccount NewAccount)
      {
                  Link_t Curr;
                Curr=Link;
                Curr->Account=NewAccount;     
 
                if(Pred!=NULL)
                {
                      Curr->Link=Pred->Link;       
                        Pred->Link=Curr;
                }   
              else
                {
                        Curr->Link = Start;
                        Start = Curr;
                }

      };// end Insert     
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      void Search4Pred(Link_t &Pred,Link_t Start, cAccount Account)
      {
              bool Done=false;
                Link_t Curr;
                Curr=Start;
                Pred=NULL;     

              while((Done!=true)&&(Curr!=NULL))
                {
                          if(Curr->Account.compID2ID(Account)>0) 
                        {
                              Pred=Curr;
                                Curr=Pred->Link;
                        }
                        else
                        { Done=true;}
                }//end while
      }// end Search4Pred     
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      void Add(Link_t &Avail,Link_t &Start, cAccount NewAccount)
      {
              Link_t Pred;

                Search4Pred(Pred,Start,NewAccount);             
                Insert(Start,Pred,Avail,NewAccount);

          }// end Add     
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      void Load(Link_t &Start,Link_t &Avail)
      {
              Filename_t Filename;
                Infile_t Infile;
                Link_t Curr=0;
                Link_t Pred=0;
              cout<<"Program Starting.........."<<endl;
                cout<<"Begining Load.........."<<endl<<endl;
                cout<<"Enter the name of the data file to be used:"<<endl; 
                cin>>Filename;
                Infile.open(Filename,ios::in);
                cAccount NewAccount;
                NewAccount.Read(Infile);
                while(!Infile.eof())
                {
                      Add(Avail,Start,NewAccount);
                        NewAccount.Read(Infile);

                }//end while
 
                Infile.close();
                cout<<"Read Complete........."<<endl;
              cout<<"Load Complete........."<<endl;

      };//end load
 //_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      void Display(Link_t Start, Link_t Avail)
      {
              Link_t Curr;
                Curr=Start;
                Name_t choice;
                cout<<"Would you like to view the output file?"<<endl;
                cout<<"(YES or NO)"<<endl;
                cin>>choice;

                if(strcmp(choice,"YES")==0||strcmp(choice,"Yes")==0||strcmp(choice,"yes")==0)
                {
                          cout<<setw(20)<<"ACCOUNT-DATA"<<endl<<endl;     

                        while(Curr!=NULL)                                           
                        {
                              Curr->Account.Display();
                                Curr=Curr->Link;

                        }//end while

                          cout<<endl;
                          cout<<"Moving to next process.........."<<endl<<endl;

                }//end if
                else
                {
                      cout<<"Very Well.........."<<endl;
                      cout<<"Moving to next process.........."<<endl<<endl;
                }

      };// end Display
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
      void Print(Link_t Start,Link_t Avail)
          {
              Link_t Curr;
                Curr=Start;
                Filename_t Filename;
                Outfile_t Outfile;
                cout<<"Enter the name of the output file: "<<endl;
                cin>>Filename;
                Outfile.open(Filename,ios::out);
                Outfile<<setw(20)<<"ACCOUNT-DATA"<<endl<<endl;

                while(Curr!=NULL)
                {
                      Curr->Account.Print(Outfile);
                        Curr=Curr->Link;

                }//end while     

                Outfile.close();
                cout<<"Write Sucessful.........."<<endl<<endl;

      };// end Print
//*************************************************************************************************
                                                  /* END OF SOURCE CODE */
//*************************************************************************************************

Help with a structure program

by endframe at 07:09 AM, 03/08/2010

Hello all, like always : D

I'm working on a structure program that has an array (m) that asks the user to enter its values, and then it transfers the even numbers to an array (even) and the odd to another (odd). Both (evan) and (odd) arays are in a structure (x) ; plus, I have made another structure (y) that is connected to (x) and has it same attributes.

My problem is, that after I run the program and add the numbers, I don't get the values in the (odd) and (even) arrays ; but instead I get their memory addresses I guess!

The code is:

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

struct x
{
int even[20];
int odd[20];
int countEven;
int countOdd;
};

main()
{
 int m[20],i,sum=0;

struct x y;

y.countEven = 0;
y.countOdd = 0;

 for (i=0;i<20;i++)
 {
  printf("\n Enter No.[%d] = ",i);
  scanf("%d",&m[i]);
  sum+=m[i];

if (m[i] % 2 == 0)
          y.even [y.countEven++]=m[i];
else
          y.odd [y.countOdd++]=m[i];
}
cout<<"Even numbers are:"<<y.even<<endl;
cout<<"Odd numbers are:"<<y.odd<<endl;

return ( 0 ) ;
}

Plus in the (cout) area at the end of the program, I wanna add more cool things that displays higher/lower numbers in both arrays, and also the total count/sum of both arrays, so the program will display these things after adding the values by the user:

- Even numbers are: ------------
- Odd numbers are: -------------
- Higher even number: ---------
- Lower even number: ----------
- Higher odd number: -----------
- Lower odd number: -----------
- The sum of even numbers: -------
- The sum of odd numbers: --------

Access class member function pointer from another class

by jakesee at 06:38 AM, 03/08/2010

Hi,

May I ask what is the correct syntax to achieve the following function pointer pattern?

I keep getting
error C2064: term does not evaluate to a function taking 0 arguments

Thank you.

class Apple
{
public:

        Apple(int i)
        {
                if(i == 1)
                {
                        juicer = &Apple::one;
                }
                else if(i == 2)
                {
                        juicer = &Apple::two;
                }
        }

        int (Apple::*juicer)();

        int one()
        {
                return 1;
        }

        int two()
        {
                return 2;
        }

        int internaljuicer()
        {
                this->juicer();
        }
};

class Basket
{
public:
        Basket(Apple* a)
        {
                apple = a;
        }

        Apple* apple;

        int getjuicer()
        {
                apple->juicer();
        }
};

int main()
{
        Apple apple(1);
        Basket basket(&apple);

        std::cout << basket.getjuicer() << std::endl;

        return 0;
}

Slick way to test if UI is loaded (C++ mac os x)?

by EricDLundquist at 06:24 AM, 03/08/2010

Currently I'm using the way posted below which works but it sure isn't elegant. Can anyone think of a way to test if the UI has loaded without using system() or popen() in c++





FILE * fp;
        char inputArray[100];
        fp = popen("ps aux | grep  SystemUIServer | grep Library | awk '{print $11}'", "r+");
       
       
        while (fgets(inputArray,sizeof,inputArray, fp)){
       
        }
       
       
       
        stringstream UIConv;
        UIConv << inputArray;
        UIDidLoad = UIConv.str();
       
       
       
       
        if ( UIDidLoad != "/System/Library/CoreServices/SystemUIServer.app/Contents/MacOS/SystemUIServer\n"){
               
               
                return 1;
}

help with homework

by savvas15 at 05:18 AM, 03/08/2010

hey guys! i am new to c++ and i need help with the following code. we are suppose to write a program and check if a word is palindrome or not.


#include <iostream>
using namespace std;

int IsPalindrome(int []);


void main()
{
        char word[25];

        cout <<" Enter a word: ";
        cin>> word;

        if (IsPalindrome(word)==1)
                cout<<" Is a palindrome ";
        else
                cout<<" Is not a palindrome "
                        <<"\n";

        system("pause");
}       

int IsPalindrome(char str1 [])
{
        int i,counter=0;

        for(i=0; str1[i]!='\0'; i++);

        for(i--; i>=0; i--)
                if (str1[i-1]==str1[i])
                        counter++;
                       
        return counter;
               
}

how to store tridiagonal matrix in c++

by sssouljah at 02:13 AM, 03/08/2010

Hello i was wondering how to store a tridiagonal matrix in c++
i know i have to use three arrays for the upper lower and diagonal terms, but how do i then use parenthesis operator to access single elements of the matrix when it is stored as three separate arrays....also how would i code a tridiagonal matrix multliplication with a vector?

thanks for your help

Problems with template friends

by dilas at 00:53 AM, 03/08/2010

I have such a problem:
when I write:
template<bool b> void foo(void);

template<bool b> class B
{
                friend void foo<b>(void);
};

template<bool b>
void foo(void){};
everything works just fine.
But when I incapsulate all this in another class, I receive errors:
struct C
{
        template<bool b> void foo(void);
        template<bool b> class B
        {
                friend void C::foo<b>(void);
        };
};

template<bool b>
void C::foo(void){};
.
In Visual C++ 2008 I get these errors:
error C2975: 'b' : invalid template argument for 'C::foo', expected compile-time constant expression;
error C2245: non-existent member function 'C::foo' specified as friend (member function signature does not match any overload).

What do I do wrong?

ID3DXMesh->GetFVF() help.

by HealBrains at 00:30 AM, 03/08/2010

Hey guys,

I have a quick question:

When I call DWORD dw = pMesh->GetFVF();, how do I determine what flags the DWORD represents?

For example, if I call that function and dw == 18, how do I determine which FVF values the '18' represents?

Thanks for your time!

EDIT: I forgot to mention that I'm loading the mesh from a .x file, so I'm not explicitly setting the vertex format anywhere.

Binary search trees

by kip2johnny at 00:27 AM, 03/08/2010

I would to get assistance on a problem involving binary search trees.writting a search algorithm and a pseudocode of a 5 node binary search tree

I need your help

by munadel at 00:23 AM, 03/08/2010

In a C++ function
How to check if the minimum and maximum values of an array are not equal and the minimum and maximum values of the array are not adjacent to one another.
Also the minimum value occurs exactly once in the array and the maximum value occurs exactly once in the array.

Need help on reading txt file into 2D array.

by Menathradon at 23:37 PM, 03/07/2010

Hello All,

I seem to be having a relatively small problem with a Maze program I'm working on. Basically, I read a txt file containing a maze into a 12 x 12 2D array, but the problem is when I try to display it, none of the white spaces that are in the maze show up. I know it has something to do with the getline() function, but I have no clue as to where to put it.

Here is what an example of a txt file used contains:

~~~~~~~~~~~~
~ =  ?  *~
~ = ^ ? ^ *~
~ = ^ ? ^ *~
~  ^  ^ =~
~***^~~~^ =~
~        =~
~ ===???^^^~
~        ^~
~~  ~~    ^~
~    ~  $~
~~~~~~~~~~~~

Here is my code so far:

#include "Maze.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
 
using namespace std;
 
Maze::Maze()
{
  mazeStore[12][12] = ' ';
}

int Maze::inputMaze()
{
  string fileName;
  char ch;


  cout << "Enter the file name: ";
  cin >> fileName;

  ifstream inFile;
  inFile.open(fileName.c_str());

  if (!inFile)
  {
      cout << "File could not be opened." << endl;
      exit(1);
  }
  else
  {
      while (!inFile.eof())
      {
        for (int i = 0; i < 12; i++)
        {
            for (int j = 0; j < 12; j++)
            {
              inFile >> mazeStore[i][j];       
            }
        }
      }
      inFile.close();
  } 
}

void Maze::outputMaze()
{
  cout << "MAZE:\n";
  cout << "          111\n";
  cout << " 123456789012\n";
   
  for(int a = 0; a < 12; a++)
  {
      for(int b = 0; b < 12; b++)
      {       
        cout << mazeStore[a][b];
      }
      cout << endl;
  }
  return;
}

Thanks in advance for any help given!

[ex-hijack] macro usage

by aditya.kaole at 23:31 PM, 03/07/2010

Hi,

Need some help regarding the macro usage.

I've a case where the parameter to be passed to the macro function is not known till the point it is called.

example: (continuing the example quoted below)
- number "12" passed to the " DEFINE_FUNC( n )" macro is determined at the time of execution.

I cannot pass a string/int var from the macro
(i.e. i cannot use

int num = 12;
DEFINE_NUM(num);
)

Can you please help me and share any solution for such situation?

Thanks in advance!
Aditya



Quote:

Originally Posted by Duoas (Post 539703)
Actually, it is possible. You need to use token concatenation.
#define DEFINE_FUNC( n ) void func_ ## n()

You would use it in the normal way:
DEFINE_FUNC( 12 );

The preprocessor would turn that into:
void func_12();


While I can't imagine why you want to do this, there are, in fact, legitimate reasons to do token concatenation (which goes a long way into explaining why the preprocessor can do it at all).

Hope this helps.

Subtracting unsigned number beyond zero

by m26k9 at 22:36 PM, 03/07/2010

Hello,

I did search around and there are few examples about this situation (not much as I would have expected though), but I want to know the procedure or how to find the solution.

Basically I have a 32-bit UNSIGNED register. I want to know how to calculate the value when I subtract 1 when the value is zero (all zero bits).

Any reference to a tutorial about this specific case or explanation is appreciated.

Cheers.

Program help

by tarheelfan_08 at 21:43 PM, 03/07/2010

Can someone please advise me as to why my assignment is not working? I am doing the exact same thing I did on another assignment and for some reason it wont work.

Assignment
1. You are a programmer that works for a local bank. You are creating classes to be used in the class library for this bank for all of its programs. You will also create a main() to test your new classes.

Talking to the bank manager you find out that your bank keeps track of Accounts and that there are more than one type of Account. There are CheckingAccounts, SavingsAccounts, and CreditCardAccounts.

(Credit card accounts are actually called line of credit accounts in the real world. But, let’s call them this here to make it clearer.)

You learn that all of the accounts are often grouped together and treated the same in many reports. So, they all need to inherit from the account class.

Account Class:
Attributes/data members
number (an integer)
balance (a double)
rate (a double)

Behaviors/member functions:
1) accessor (get) and mutator (set) functions for all attributes.
2) ApplyInterest()
Note: The ApplyInterest() function needs to be a virtual function. It is going to be overridden in the subclasses.

Constructor(s):
This class must have a constructor that accepts all of the data to create an Account and initializes its data members.

Validation in member functions/ Business Rules:
1) Rates should be between .01 and .18 (it is an interest rate as a decimal)
2) Balances should never be allowed to be set to a negative value.


CheckingAccount Class:
This class inherits from the Account class

Attributes/data members
checknumber (an integer) [representing the last check number written/processed.]
pin (an integer)

Behaviors/member functions:
1) accessor (get) and mutator (set) functions for all attributes.
2) ApplyInterest(), this function should take the balance and multiply it by the rate to find the interest this period…then add it to the existing balance. Print a message to the user with the amount in this format “2.35 has been added to checking”

Constructor(s):
This class must have a constructor that accepts all of the data to create a CheckingAccount and initializes its data members. (This includes all of the data it needs to pass to the Account class constructor or set directly for the account class from this constructor.)

SavingsAccount Class:
This class inherits from the Account class

Attributes/data members

Behaviors/member functions:
1) accessor (get) and mutator (set) functions for all attributes.
2) ApplyInterest(), this function should take the balance and multiply it by the rate to find the interest this period…then add it to the existing balance. Print a message to the user with the amount in this format “5.01 has been added to savings”


Constructor(s):
This class must have a constructor that accepts all of the data to create a SavingsAccount and initializes its data members. (This includes all of the data it needs to pass to the Account class constructor or set directly for the account class from this constructor.)


CreditCardAccount Class:
This class inherits from the Account class

Attributes/data members
cardnumber (a string)

Behaviors/member functions:
1) accessor (get) and mutator (set) functions for all attributes.
2) ApplyInterest(), this function should take the balance and multiply it by the rate to find the interest this period…then add it to the existing balance. Print a message to the user with the amount in this format “5.23 interest has been charged to this credit card on its unpaid balance”

Constructor(s):
This class must have a constructor that accepts all of the data to create a CreditCardAccount and initializes its data members. (This includes all of the data it needs to pass to the Account class constructor or set directly for the account class from this constructor.)


Main()

1) In main for this program create a checking account, savings account, and credit card account for a customer with test data as follows and place them in an array:

(type) account # balance rate checknumber pin cardnumber
(checking) 832443 560.10 .02 5854 123
(savings) 832443 1020.58 .04
(credit card) 832443 78.00 .16 1238201293731133

2) Print out all of the data for the accounts for the user.
3) Use a loop and call the ApplyInterest() method to add interest to the balance and print appropriate messages to the user.
4) Print out all of the data for the accounts for the user.

Account Class
#ifndef ACCOUNT_H
#define ACCOUNT_H

#include <iostream>
#include <fstream>
#include <iomanip>
#include <functional>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;

//Account Class
class Account {
private:

        int number;
            double balance;
                  double rate;
                double interest;
                double NewBalance;

public:
        Account(); // Constructor
        Account(int, double, double) ;
              void setBalance(double);
                void setRate(double);
                                void setNumber(int);

                                int getNumber();
                double getBalance();
                double getRate();
                                void valid_rate(double);
                                virtual void ApplyInterest();
                               
                                void operator +=( double );
                        void operator -=( double );
                              void operator ++ ();
                };     
//-----------------------------------------------------------------------------
//class definition
        Account::Account() {
                number = 0;
                balance = 0;
                rate = 0;
        }

        Account::Account(int number, double balance, double rate) {
                Account::number = number;
                Account::balance = balance;
                valid_rate(rate);
                }

void Account::setNumber(int number) {
    Account::number = number;
}

void Account::setBalance(double balance) {
    Account::balance = balance;
}

void Account::setRate(double rate) {
        valid_rate(rate);
}

int Account::getNumber() {
    return number;
}
double Account::getBalance() {
    return balance;
}
double Account::getRate() {
    return rate;
}

void Account::valid_rate(double rate) {
        if (rate >=.01 && rate <= .18)
                Account::rate=rate;
        else {
                Account::rate=0;
                cout << "WARNING! You have entered an invalid rate!\n";
        }
}

void Account::operator += ( double dValue ) {
        setBalance( getBalance()+ dValue );
                //return this;
    }
void Account::operator -= ( double dValue ) {
        setBalance( getBalance() - dValue );
                //return this;
    }


#endif

Checking Classk
#ifndef CHECKING_H
#define CHECKING_H

#include "Account.h"

//Checking Class
class Checking {
private:
                Checking myChecking[1];
        int CheckNumber;
            int CheckingPin;



public:
        Checking(); // Constructor
        Checking(int, int) ;
                      void setCheckNumber(int);
                                void setCheckingPin(int);

                                int getCheckNumber();
                int getCheckingPin();

                };     
//-----------------------------------------------------------------------------
//class definition
        Checking::Checking() {
                CheckNumber = 0;
                CheckingPin = 0;
               
        }

        Checking::Checking(int CheckNumber, int CheckingPin) {
                Checking::CheckNumber = CheckNumber;
                Checking::CheckingPin = CheckingPin;
               
                }

void Checking::setCheckNumber(int CheckNumber) {
    Checking::CheckNumber = CheckNumber;
}

void Checking::CheckingPin(int CheckingPin) {
    Checking::CheckingPin = CheckingPin;
}


int Checking::getCheckNumber() {
    return CheckNumber;
}
int Checking::getCheckingPin() {
    return CheckingPin;
}

void Account::ApplyInterest() {
                interest = rate * balance;
                NewBalance = interest + balance;
                cout << interest << " has been added to checking.\n\n";
}

#endif

Credit Class
#ifndef CHECKING_H
#define CHECKING_H

#include "Account.h"
//Checking Class
class Credit {
private:

    Credit myCredit[1];   
        string CardNumber;

public:
        Credit(); // Constructor
        Credit(string) ;
                      void setCardNumber(string);

                                string getCardNumber();


                };     
//-----------------------------------------------------------------------------
//class definition
        Credit::Credit() {
                CardNumber = " ";
                               
        }

        Credit::Credit(string CardNumber) {
                Credit::CardNumber = CardNumber;
                               
                }

void Credit::setCardNumber(string CardNumber) {
    Credit::CardNumber = CardNumber;
}


string Credit::getCardNumber() {
    return CardNumber;
}


void Account::ApplyInterest() {
                interest = rate * balance;
                NewBalance = interest + balance;
                cout << interest << " 23 interest has been charged to this credit card on its unpaid balance.\n\n";
}

#endif

Saving Class
#ifndef SAVING_H
#define SAVING_H

//Customer Class
class Saving {
private:
Saving mySaving[1];
public:
                };     

void Account::ApplyInterest() {
                interest = rate * balance;
                NewBalance = interest + balance;
                cout << interest << " has been added to checking.\n\n";

}
#endif

Main
#include "Account.h"
#include "Checking.h"
#include "Saving.h"
#include "Credit.h"
using namespace std;

int main() {

        int current_cust=0;
        Checking *myChecking[1];
        Saving *mySaving[1];
        Credit *myCredit[1];

        Checking myRate;
                myChecking[0] = new Checking(832443, 560.10, .02, 5);
                mySaving[0] = new Saving(832243, 1020.58, .04);
                myCredit[0] = new Credit(832443, 78.00, .16, 1238201293731133);

        cout << "__________________________________________________________\n"<< endl;

        for (int c=0; c<1; c++)
                myChecking[c]->ApplyInterest();

                cout << "__________________________________________________________\n"<< endl;

        for (int s=0; s<1; s++)
                mySaving[s]->ApplyInterest();

                cout << "__________________________________________________________\n"<< endl;

        for (int x=0; x<1; x++)
                myCredit[x]->ApplyInterest();

        cout << "__________________________________________________________\n"<< endl;

        return 0;
}

STL container to hold generic variables

by evstevemd at 21:34 PM, 03/07/2010

Hi,
I'm finding generic container like vector but that can hold any variable just like a Python list. Thanks

Array loop - quick question

by bluerosebuddha at 19:15 PM, 03/07/2010

Hello,

Can someone break down what this array loop means exactly? Mathematically I can't make any sense of it. I've reread this section of my book multiple times, but it's not sinking in.

int alpha[a];
int j;

for(j = 0; j< 5; j++)
{
 alpha[j] = 2 * j;

 if(j % 2 == 1)
    alpha[j - 1] + j;
}

I'm new to C++ ; this was quiz question I missed. The correct answer was alpha = {3, 2, 9, 6, 8} - just not sure how/why! TY.

Prime and Factor problem...

by ajjg123 at 17:16 PM, 03/07/2010

Here is the prompt for my assignment

Your third assignment is to write a C++ program that will print out the primes numbers between 2 and 100. However, you must use two functions in your program.

The first function, factor, takes an int, n, and returns two factors of n whose product is n. For example, if n is 36, factor could return 6 and 6 (or 2 and 18, or 4 and 9, ...). If n is prime, factor should return 1 and n (in that order). If n is not prime, factor should not return 1 and n, but find two non-trivial factors. The factor function should have a return type of void and use call-by-reference parameters to return the two factors.

The second function, prime, should return a Boolean value - true if the argument is prime, and false if it is not prime. Since a good programmer is lazy, the prime function should call the factor function instead of doing any work itself.

Finally, the main program should loop through all the numbers between 2 and 100, and print out just those that are prime. The main program should call the prime function appropriately, which in turn calls the factor function.


_____________________________________________
I think I'll be able to figure out how to find the prime numbers, but I have no clue how to find factors of a number

Newbie Linking Issue

by yottameter at 17:12 PM, 03/07/2010

I've run into linking problems before, so I thought I had them figured out. This one I'm using every tool I have, but I can't seem to identify what the issue is.

Did a build from the yaml site yesterday, I keep getting this linking error at runtime. I set LD_LIBRARY_PATH, but as you can see the shared object that is missing with ldd is in the path. Am I missing something here?

$ g++ -fPIC -Wall -lyaml-cpp main.c -L$YAMLCPP/yaml-cpp/build-I$YAMLCPP/yaml-cpp/include
$ a.out
a.out: error while loading shared libraries: libyaml-cpp.so.0.2: cannot open shared object file: No such file or directory
$ ldd a.out
        libyaml-cpp.so.0.2 => not found
        libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00000034ce400000)
        libm.so.6 => /lib64/tls/libm.so.6 (0x00000034cbe00000)
        libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00000034ce200000)
        libc.so.6 => /lib64/tls/libc.so.6 (0x00000034cbb00000)
        /lib64/ld-linux-x86-64.so.2 (0x00000034cb700000)
$ ls $LD_LIBRARY_PATH
CMakeCache.txt      CTestTestfile.cmake  libyaml-cpp.so.0.2.4  yaml-cpp.pc
CMakeFiles          libyaml-cpp.so      Makefile              yaml-reader
cmake_install.cmake  libyaml-cpp.so.0.2  util

Pointer to a vector

by tom384 at 16:52 PM, 03/07/2010

Hi guys,

I'm having trouble using a pointer to a vector<float>, it doesn't seems to be responding as I'm expecting it to.

Probably a silly mistake on my behalf, but would anyone kindly point it out please.

vector<float>* t_matrix;
...
cout << "get_t_matrices 0: " << Character::anim.get_animations()[j].get_t_matrices()[0].size() << endl;
t_matrix = &(Character::anim.get_animations()[j].get_t_matrices()[0]);
cout << "t_matrix size: " << (t_matrix)->size() << endl;

get_t_matrices() returns a vector<vector<float>>

Line 3 outputs "get_t_matrices 0: 16" to the console.
But line 5 outputs "t_matrix size: 0".

Can anyone explain why t_matrix doesn't seem to be pointing to the value on line 4, please?

little question

by HelloMe at 16:04 PM, 03/07/2010

Hello everyone...

I have 2 questions and it would be great if you guys can help me on these.

I wrote a factorial program and it works already.
The problem is when it comes to higher outputs.

For example:
11 P 5 = 55440 // this works so far
but
13 P 5 = 154440 // but my output is 47917

Im using already long instead of integer.
Can someone help me out on this?

Second thing is, how do i avoid that someone will enter letters? :-)

Btw my code is:

#include <iostream>
using namespace std;

long factorial (long n)
{
  if (n > 1)
  return (n * factorial (n-1));
  else
  return (1);
}

int main ()
{

        cout<< " WELCOME TO THE 2 BASED FACTORIAL CALCULATOR " << endl << endl;

start:;

  long number;
  cout << "Please type a number: ";
  cin >> number;

  long number2;
  cout << endl << "Please type a 2nd number: ";
  cin >> number2;

  long number3;

      number3 = factorial(number) / factorial(number - number2);

          {
 
          if (number < number2)

          {
                 
                  cout<< "Please let the first number be bigger than the second number." << endl << endl;
                  goto start;

          }

          if (number >= number2)

          {

                  cout << endl << number << " P " << number2 << " = " << number3 << endl << endl;
          }

  }

  goto start;

  return 0;
}

Could This Program Be Created?

by libby71 at 16:00 PM, 03/07/2010

This is a non technical question, I am not a programmer, but I have a question on creating a C++ program, I hope somone could answer for me, and to see if this could be done in C++, so I could hire someone to make this for me.
I am using a program called gpsmapedit, would it be possible to make a program in C++ that will automatically run certain functions of gpsmapedit, while I am gone during the day?
Any help would be greatly appreciated.
Thank you,
Dave

hello everyone..i need help.....=\

by marshella at 14:28 PM, 03/07/2010

i need help with my assignment...i'm so new with this c++ programming...i only know how to do up to division only for this question... and for question two,i really have no idea how to start...can someone help me out and try to make me understand how the code will works...i really need some help...

QUESTION 1

Write a calculator program that allows the user to select which operation they would like to perform such as:
•Addition
•Subtraction
•Multiplication
•Division
•Modulus
•Square (x2)
•Square root ( )
•Convert Celsius to Fahrenheit (Fahrenheit = 1.8 Celsius +32)
•Convert Celsius to Kelvin (add 273.15 °)
•Convert Fahrenheit to Celsius (Celsius = (F-32) x (5/9))
•Convert Fahrenheit to Kelvin (Kelvin = 5/9 x (Fahrenheit - 32) + 273)

Make sure your program contains menu and will keep on looping until the user enter a specific value to end it. Please use Functions to do the calculation. You might want to use switch for the menu.


Question 2

A parking garage charges a RM2.00 minimum fee to park for up to three hours. The garage charges an additional RM0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24 hour period is RM10.00. Assume that no car parks for longer than 24 hours at a time. Write a program that will calculate and print the parking charges for each of 3 customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of yesterday’s receipts. The program should use FUNCTION to determine the charge for each customer.

Deleting Char in string?

by macman101 at 14:15 PM, 03/07/2010

Hey guys, I need a little help. I'm writing a palindrome checker for fun, and I need to ignore/delete spaces and punctuation. I compare my two strings using strcmp and I use pointers to go through the first part of the program. I'm now stuck trying to factor out the spaces and punctuation, and I'm guessing I will have to do something b4 the strcmp is called. What should I do to delete all the spaces and punctuation?

Thanks,
MacMan101
Hey everyone, I have a simple simple problem that is literally driving me insane.

Basically, I have a database of numbers seperated my spaces. I just took a segment of my code because I am soooo completely lost with the output!!

If the database is:

1 2 3 9 7 6 4 5 6 7

I don't understand why my output is 1 for every single line??? How is the sscanf statement not taking the next string??

Someone please help I am desperate!!


#include <stdio.h>

main()
{
       
        char buffer[20000];
        char pid_temp[501], arrival_time_temp[501], CPU_burst_temp[501], IO_burst_temp[501];       
        FILE *fp;
       
        fp = fopen("CPULoad.dat", "r");
        fgets(buffer, 20000, fp);       
       
        fp = fopen("CPULoad.dat", "r");
        fgets(buffer, 20000, fp);
       
        sscanf(buffer, "%s", CPU_burst_temp);
        printf("%s\n", CPU_burst_temp);
        sscanf(buffer, "%s", CPU_burst_temp);
        printf("%s\n", CPU_burst_temp);
        sscanf(buffer, "%s", CPU_burst_temp);
        printf("%s\n", CPU_burst_temp);
        sscanf(buffer, "%s", CPU_burst_temp);
        printf("%s\n", CPU_burst_temp);
        sscanf(buffer, "%s", CPU_burst_temp);
        printf("%s\n", CPU_burst_temp);
        sscanf(buffer, "%s", CPU_burst_temp);
        printf("%s\n", CPU_burst_temp);
        sscanf(buffer, "%s", CPU_burst_temp);
        printf("%s\n", CPU_burst_temp);
       
        close(fp);
}

problem with sockets

by vbx_wx at 13:39 PM, 03/07/2010

sendfile(string path)
                {
                        int length;
                    char buffer[10];
                        ifstream in(path.c_str() , ios::binary);
                        in.seekg(0 , ios::end);
                        length = in.tellg();

                        in.seekg(0 , ios::beg);
                        stringstream infofile;
                        string name = splitname(path);
                        infofile <<"info" << " " << name << " " << length;
                        string infoBuffer = infofile.str();

                        send(infoBuffer);

                        while(!in.read(buffer , 1).eof())
                        {
                                cout <<::send(sock , buffer , 1 , 0);

                        }
                        cout << "File sent" << endl;
                }

receivefile(string path)
                {
                        char buffer[10];
                        string recvBuffer;
                        ofstream in(path.c_str() , ios::binary);

                        recv(recvBuffer);

                        if(recvBuffer.compare(0 , 4 , "info") == 0)
                        {
                                string name = getFileName(recvBuffer);
                                string size = getFileSize(recvBuffer);
                                cout << "File name is: " << name << endl;
                                cout << "Size of file is: " << size << endl;
                        }

                        while(int i = ::recv(sock , buffer , 1 , 0) > 0)
                        {
                                cout << i;
                                in.write(buffer , 1);
                        }
                        cout << "File received" << endl;
                }

my problem is that it sends and receives the file but only if i stop the program,if not it just remains stuck in the while loop in receive() function ....why is that ?

Instance of vector

by tango2009 at 11:08 AM, 03/07/2010

I am trying to make an istance of this

Vector2f(20,20)

How to I go about this?

Array truble

by Tech B at 10:25 AM, 03/07/2010

I downloaded a dll for head tracking, and have been trying to use it for some time now. I am trying to make a python script that uses it and am getting errors. This is the post.

I posted it in the python forums, and no replies yet, since this deals with C++ I figured I would post in here to looking for some help.

String Array

by nerdy900 at 10:24 AM, 03/07/2010

I was working on the being of a cash register and I was testing this portion of my code. It compiles, but when I input my first items name I get a windows error and the program ends. I would appreciate any help an/or explanation.

#include <iostream> // allows output and input
#include <iomanip>  //allows i/o manipulation
#include <stdlib.h>
#include <fstream>  // allows file i/o
#include <string>  // allows the use of strings


//declares variables
int current_input_number;
int number_of_items;   




main()
{
    using namespace std;

    system("COLOR 0a"); // changes color
   
    //declares an array of strings   
    string item_name[number_of_items];
   
    cout << "How many items does the customer have? \n";
    cin >> number_of_items;
   
   
    for (current_input_number = 1; current_input_number < number_of_items; current_input_number++)
    {
        cout << "Please enter product number " << current_input_number << '\n';
      cin >> item_name[current_input_number]; 
       
    }
   
    for (current_input_number = 1; current_input_number < number_of_items; current_input_number++)
    {
      cout << item_name[current_input_number] << '\n'; 
       
    }
   

    cin.ignore(2);
    return 0;
}

Hijack post -- write a program.

by sonalsinha at 10:18 AM, 03/07/2010

write a program in c++ using classes to perform the addition operation at the beginning

a year to make a web browser, how do i start?

by fallendream at 10:15 AM, 03/07/2010

hey,
to start with heres the backdrop;
me and a friend from school have a year to create a fully working web browser and for this i think C++ would be best.
heres where i need help, i have no experience with C++ and i need to learn it from near-scratch.
so what steps should i take and how should i start it?
should i sit and learn C++ first or learn as i progress?
what programs should i use as a compiler and to write the code?
what engine should i use?

how do i incorporate all this into a program?
what other advice can you give?

Processing math equations

by squarey at 09:31 AM, 03/07/2010

Hi Guys

Does anyone know of any classes that process string mathmatical equations ? E.g. 2+2(6*5(2-1)) - It is specified on the command line and stored as a string.

Need some help with a homework program

by Vou at 09:23 AM, 03/07/2010

Hello everyone,
I'm currently in college for Game programming and I'm coming in having known nothing about programming at all. I'm currently learning Object Orientated C++ Programming. I have been at this one problem for two weeks and I'm completely stumped. I currently have three files the main cpp file, the cpp file with all the information, and then the header file. I'm completely stuck on how to properly call the functions into main here are the following codes. This is just the first of many problems I am working on. All help is highly Appreciated as I'm trying to do this as I've gotten little help from my professor. Whom I believe thinks I should figure this out on my own. But with time restraints, it is exceedingly difficult and I fully intend on graduating and getting into the industry. Again thank you ahead of time for any help in helping me fix this and any future questions.

header:
#define Asteroids_h

class Asteroid
{
        private:
        int astSpeed;
        int astSize;
       

        Asteroid () {}
public:

void displayStats(int AsteroidNumber);
void setSize( int astSize);
void setSpeed(int astSpeed);

int setSpeed()
{
        return astSpeed;
}
int setSize()
{
        return astSpeed;
}

};

core file:

#include <iostream>
using namespace std;

class Asteroid
{
        int astSize;
        int astSpeed;
        int AsteroidNumber;
public:
        Asteroid ( int Size, int Speed, int AsteroidNumber )
        {
                setSpeed( Size);
                setSize (Speed);
               
        }
        int getSize()
        {
                return astSize;
        }
        int getSpeed()
        {
                return astSpeed;
        }
       

        void displayStats(int AsteroidNumber)
               
        {
               
               
                cout<< "Asteroids " << endl;
                cout<< " Asteroid number " << AsteroidNumber << endl;
                cout<< " Size " << astSize << endl;
                cout<< " Speed " << astSpeed << endl;
        }
        void setSize(int Size)
        {
                astSize = Size;
        }
       
        void setSpeed(int Speed)
        {
                astSpeed = Speed;
        }
       
};

and the main:

#include <iostream>
using namespace std;
#include "Asteroids.h"

int main()

{
       
        Asteroid firstAsteroid();
        Asteroid secondAsteroid();
       
       
        firstAsteroid.setSpeed(20);
        secondAsteroid.setSpeed(3);
        firstAsteroid.displayStats(1);
        secondAsteroid.displayStats(2);

char wait;
cin>> wait;

       
return 0;
}
the current error(s) I have thus far is the following:

asteroidproject\asteroidmain.cpp(9) : error C2664: 'Asteroid::Asteroid(const Asteroid &)' : cannot convert parameter 1 from 'int' to 'const Asteroid &'
1>        Reason: cannot convert from 'int' to 'const Asteroid'
1>        No constructor could take the source type, or constructor overload resolution was ambiguous
1>e:\cit43\asteroidproject\asteroidmain.cpp(10) : error C2664: 'Asteroid::Asteroid(const Asteroid &)' : cannot convert parameter 1 from 'int' to 'const Asteroid &'
1>        Reason: cannot convert from 'int' to 'const Asteroid'
1>        No constructor could take the source type, or constructor overload resolution was ambiguous

1st VC++ programme

by jeevsmyd at 08:51 AM, 03/07/2010

I have been doing TC++ programing for the last 2 years.. This evening all of a sudden I made the switch to vc++.. here is the code.. my first ever Visual C++ programme.. it is compiling without errors but the console window poped and disappeared quickly.. what is wrong? something similar to getch() missing or what?

 // test2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
        cout<< "Hello world";
        return 0;
}

Help with calculator

by eddan at 06:44 AM, 03/07/2010

// Calculator.cpp : Defines the entry point for the console application.
//

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

int  GetNumber1();
void GetMathematicalOperation();
int  GetNumber2();
int CalculateResult();
int PrintResult();

int main()
{
        GetNumber1();
        GetMathematicalOperation();
        GetNumber2();
        CalculateResult();
        PrintResult();
   
        int CalculateResult( int x, char chOperation, int y);
        int PrintResult( CalculateResult( int x, char chOperation, int y));
}

int GetNumber1()
{
        cout << "Enter first number: ";
        int x;
        cin >> x;
        return x;
}

char GetMathematicalOperation();
{
        cout << "Enter operator: ";
        char chOperation;
        cin >> chOperation;
        return chOperation;
}

int GetNumber2();
{
        cout << "Enter second number: ";
        int y;
        cin >> y;
        return y;
}

ERROR in compiler:
1>------ Build started: Project: Calculator, Configuration: Debug Win32 ------
1>Compiling...
1>Calculator.cpp
1>d:\c++projects\calculator\calculator\calculator.cpp(23) : error C2144: syntax error : 'int' should be preceded by ')'
1>d:\c++projects\calculator\calculator\calculator.cpp(23) : error C2660: 'CalculateResult' : function does not take 0 arguments
1>d:\c++projects\calculator\calculator\calculator.cpp(23) : error C2059: syntax error : ')'
1>d:\c++projects\calculator\calculator\calculator.cpp(34) : error C2556: 'char GetMathematicalOperation(void)' : overloaded function differs only by return type from 'void GetMathematicalOperation(void)'
1>        d:\c++projects\calculator\calculator\calculator.cpp(9) : see declaration of 'GetMathematicalOperation'
1>d:\c++projects\calculator\calculator\calculator.cpp(34) : error C2371: 'GetMathematicalOperation' : redefinition; different basic types
1>        d:\c++projects\calculator\calculator\calculator.cpp(9) : see declaration of 'GetMathematicalOperation'
1>d:\c++projects\calculator\calculator\calculator.cpp(35) : error C2447: '{' : missing function header (old-style formal list?)
1>d:\c++projects\calculator\calculator\calculator.cpp(43) : error C2447: '{' : missing function header (old-style formal list?)
1>Build log was saved at "file://d:\c++projects\Calculator\Calculator\Debug\BuildLog.htm"
1>Calculator - 7 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Thanks!

Small header file queston ...

by wwsoft at 06:42 AM, 03/07/2010

hello , I am making a small game engine and I have 2 header files engine.h and objects.h they both include each other. However it seems that its not getting included into objects.h , what is the "right" way to fix this ?

sorry , I'm too lazy to gut out my code to make it more readable
engine.h


#ifndef ENGIN_H_INCLUDED
#define ENGIN_H_INCLUDED

using namespace std;

#include <SDL.h>
#include <SDL_image.h>
#include <SDL_mixer.h>
#include <SDL_ttf.h>

#include <math.h>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>

#include "objects.h"

using namespace std;

/// user

//Surface Copy

void drip_blit( float x, float y, SDL_Surface* source, SDL_Surface* destination );

//Render text
enum textquality { solid, shaded, blended };

SDL_Surface * drip_draw_text(TTF_Font *fonttodraw, string texts, int fgR, int fgG, int fgB,int fgA , int bgR, int bgG, int bgB, int bgA, textquality quality);

// Load

unsigned int drip_load_font(string file, int ptsize);

unsigned int drip_load_image(string file);

unsigned drip_load_music(string file);

unsigned drip_load_sound(string file);

// Get

SDL_Surface * drip_get_image(unsigned int img_num);

Mix_Music * drip_get_music(unsigned int mus_num);

Mix_Chunk * drip_get_sound(unsigned int snd_num);

TTF_Font * drip_get_font(unsigned int font_num);

// Music/Sound

void drip_play_music(unsigned int pos,int loopn);// 1- = forever 0=1 1=2 etc

void drip_stop_music();

void drip_pause_music();

void drip_unpause_music();

void drip_music_position(double pos);

void drip_play_sound(unsigned int pos);

void drip_stop_sound();

void drip_pause_sound();

void drip_unpause_sound();

void drip_fadeout_sound(float seconds);

// collisions

int drip_rect_collide(SDL_Rect a , SDL_Rect b);

unsigned int drip_rect_collide_all(SDL_Rect rect,unsigned self);

int drip_get_distance(int x1,int y1,int x2,int y2);

unsigned int drip_rect_collide_circle(int radius,int x1 ,int y1,unsigned self);

// random

void drip_randomize();

int drip_random(int low , int high);

// xlength & ylength for moving in directions - what else do you name them ? (super_ultral_directiony_move_thinga_ma_jig)

float xlength(float direction,float length);

float ylength(float direction,float length);

// map / file

string drip_map_process(string data);

void drip_file_write(char file[255],string data);

string drip_file_load(char filen[255]);//standard text

string drip_map_rawload(char filen[255]); // output in map format

string drip_string_copy(string str,int pos1,int pos2);

string drip_map_extract(string mapdata,int num);

void drip_map_exec(string cmddata);

void drip_map_execute(string mapdata);

string drip_map_load(string file);

/// System

// Start the system

SDL_Surface * init(char caption[255],int width , int height , int soundvoulme , int musicvolume);

// load up all the system resources

bool load();

// update objects

void update(SDL_Surface * screen);

// quit game and free resources

void quit();

#endif // ENGIN_H_INCLUDED
objects.h

#include <SDL.h>
#include "SDL_image.h"
#include "SDL_mixer.h"
#include "SDL_ttf.h"
#include "SDL_rotozoom.h"

#include <cstdio>
#include <cmath>
#include <vector>
#include <iostream>
#include "engine.h"

// not working ??? #include "engine.h"


#ifndef OBJECTS_H_INCLUDED
#define OBJECTS_H_INCLUDED

using namespace std;

class game_object;

namespace var
{
    extern vector<game_object*> _objects_;
    extern vector<SDL_Surface*> _img_;
    extern vector<TTF_Font*> _font_;
    extern vector<Mix_Chunk*> _sound_;
    extern vector<Mix_Music*> _music_;

    // gameplay

    extern int trigger[33];
    extern float delta;

    // settings

    extern bool quit;
    extern bool pause;

    extern int sound_volume;
    extern int music_volume;

    extern string error[2];
    extern int errorlevel;

    // screen

    extern int x;
    extern int y;
    extern int width;
    extern int height;

    // misc

    extern string data_dir;
    extern SDL_PixelFormat * format;
}

class game_object
{
    public:

    SDL_Surface* sprite;
    SDL_Rect rect;
    std::string type[3];// name , group , controller

    float x;
    float y;
    int z;
    unsigned int self;
    bool visable; // draw ?
    bool solid; // check for collisions ?
    bool remove; // kill it ?
    bool center; // draw sprite centered ?

    game_object()
    {
    }

    virtual void update()
    {
    }


    std::string get_type(int typen)
    {
        if (typen==0)
            return type[0];
        if (typen==1)
            return type[1];
        if (typen==2)
            return type[2];
    }

    SDL_Surface * get_sprite()
    {
        return sprite;
    }

    SDL_Rect get_rect()
    {
        return rect;
    }

};

/// map objects

class tile : public game_object
{
    public:

    tile(float xx,float yy,int zz,unsigned int image_num)
    {
        x=xx;
        y=yy;
        z=zz;

        sprite=drip_get_image(image_num);

        visable=1;
        solid=0;
        remove=0;
        center=0;

        type[0]="tile";
        type[1]="non-solid";
        type[2]="none";

        rect.w=sprite->w;
        rect.h=sprite->h;
        rect.x=x;
        rect.y=y;
    }

    virtual void update()
    {
    }

};

class player : public game_object
{
    public:

    float direction;
    float angle;
    float speed;
    float dspeed;
    int maxspeed;
    int turn;
    float friction;
    float acceleration;
    SDL_Surface * oldsprite;

    player(float xx,float yy,int zz,unsigned int image_num)
    {
        x=xx;
        y=yy;
        z=zz;

        direction=90;

        oldsprite=rotozoomSurface(drip_get_image(image_num),270,1,0); // change image to match with start angle

        angle=direction;
        speed=0;
        dspeed=0;
        maxspeed=2;
        friction=.0075;
        acceleration=.12;
        turn=200;

        visable=1;
        solid=0;
        remove=0;
        center=1;

        type[0]="tile";
        type[1]="non-solid";
        type[2]="none";

        rect.w=sprite->w;
        rect.h=sprite->h;
        rect.x=x;
        rect.y=y;
    }

    virtual void update()
    {
        // move

        //speed=100;

        //dspeed=speed * ( var::delta / 100.f );

        sprite=rotozoomSurface(oldsprite,angle,1,0);

        x+=xlength(direction,speed);
        y+=ylength(direction,speed);

        rect.x=x;
        rect.y=y;

        var::x=x-var::width/2;
        var::y=y-var::height/2;

        if (speed < 1)
          speed-=friction;

        if (speed > 0)
          speed-=friction;

        if (speed < 0)
          speed=0;


        Uint8 *keystate = SDL_GetKeyState(NULL);


        if ( keystate[SDLK_LEFT] )
        {
            angle+=1;
        }

        if ( keystate[SDLK_RIGHT] )
        {
            angle-=1;
        }

        if ( keystate[SDLK_UP] )
        {
            speed+=acceleration;// * ( var::delta / 1000.f );

            if (direction > angle)
                direction-=2;
            else
                direction+=2;

        }

        if ( keystate[SDLK_HOME] )
        {
            x=0;
            y=0;
        }

        if ( keystate[SDLK_END] )
        {
            speed=0;
            direction=0;
            angle=0;
        }

        if (angle > direction+360)
            direction+=360;
        if (angle < direction-360)
            direction-=360;



        if (speed > maxspeed)
            speed=maxspeed;
    }

};


#endif // OBJECTS_H_INCLUDED

using a 2D array as a 1D. got stuck!

by parisa_bala at 04:48 AM, 03/07/2010

I am a C programmer. I am working on a C++ code and translating it into C.
I got stuck in a point where I do not understand what is going on.
I would kindly ask if you would mine help me to understand these problems.

I have three problems:

1)There are two arrays with different length:

vector<double> D;
double temp[5];

//and then:

D.resize(3, temp);


Does the programmer wants to copy temp[0], temp[1], and temp[2] into D[0], D[1], and D[2] ?

2)There is a two dimensional array

vector<vector<double> > F;

it is initialized like this:

F.resize(3, temp);

Since temp[5] is a one dimensional array, is it possible to copy it into a two dimensional array?


Finally array F which is a two dimensional array is passed as a one dimensional array into a function like this:

//declaration of function
void do(vector<double> & F);

main(){

// now F which is sopposed to be a two dimensional array is used like
for(int I; i<3; i++) do(F[i]); // !!!!!!!!!!!!!


}

In C it is not possible as far as my knowledge. Is this possible in C++?

Thanks in advance for your kind help.

return 0; at the end of a main()

by MrPapas1991 at 02:25 AM, 03/07/2010

when should i use "return 0;" at the end of a main() function?

reading from text file

by aruprongs at 00:58 AM, 03/07/2010

Hi,
I'm reading from a text file and writing to another one.My problem is that the data is being written to the new file as one line..i.e., when the end of a line is reached it does not start writing a new line but continues on the same line.. Can someone please tell me how to make it write data line by line? this is my code..Any improvements and suggestions will be appreciated. Thanks
#include<iostream.h>
void main()
{
      char *buffer;
ofstream myfile;
ifstream myfile1;
myfile.open("book1.txt");
myfile1.open("book2.txt");
while(!myfile1.eof())
{
myfile1.getline(buffer,'\t');
myfile<<buffer;
}
delete [] buffer;
myfile.close();
myfile1.close();
}

3D link configuration

by bhp2005 at 00:51 AM, 03/07/2010

Hi, I have this homework problem that I need some help on:

In 3D: Given 2 links attached end to end with lengths L0 and L1 respectively, a point P0 that the first link starts at, and a point P1 that you want the end of the 2nd link to be at, write a function that finds the configurations of the links that put the 2nd link’s end at point P1.

I feel like I'm missing something because I don' t know where to start with it. I really don't even know what the problem is asking for. I'm hoping one of you comp. sci. or math geniuses will be able to help. Any tips/help would be appreciated.

Thanks in advance.

Hijack attempt - Functions

by safia qurban at 00:29 AM, 03/07/2010

i want to give a presention on functions use in code and want to give a comparision by function call by value and by reference with different cods can any one help me ,as give me these codes?

Using non standar fonts

by pato wlmc at 21:02 PM, 03/06/2010

Well, i'm developing a program, ( API ) and i'd like to use a non standar font, for some section of my program.

My question is, how can i do this, i mean, i supose i have to install the font on the user pc, but how do i do this.

THANKS!

O!! and 1 more, less important question: how do i set the "ICONQUESTION" on a dialog box, jeje, i can't figure that one out

Need help with new opencv 2.0 install

by lotrsimp12345 at 20:51 PM, 03/06/2010

I got the files to build but with this link

http://www.site.uottawa.ca/~laganier...ow/cvision.htm

the include files in step 2 don't show up anywhere.
Help appreciated.

Program Not Recognizing Input File

by wolfkrug at 17:57 PM, 03/06/2010

I am converting a console IO program to a file IO program. The program worked perfectly as a console IO. I thought I made the appropriate changes to the program. It compiles, and when I run it output does go to my output text file, but the output is the same as if the input text file was blank. No matter what I do to the input text file the output text file is the same, so somehow my program is not reading it. I know that I spelled the input file name correctly when opening it in the program. Here is the program, thanks for any suggestions.
#include <fstream>
using std::ifstream;
using std::ofstream;
using std::endl;

int main()
{
        ifstream inStream;
        ofstream outStream;

        inStream.open("infile.txt");
        outStream.open("output.txt");

        int avgRain[12], currentRain[12], x, y, z, r;

        outStream << "Please enter the average rainfall (to the nearest inch), starting with January, " << endl;
        outStream << "then February, then March, etc.  Make sure to press enter after every month." << endl;

        for (x = 0; x < 12; x++) // x used to take exactly 12 inputs
        {
                inStream >> avgRain[x];
                outStream << endl;
        }

        outStream << "What is numeral of the current month? (Jan is 1, Oct is 10, etc)" << endl << endl;

        inStream >> y;
        outStream << endl;

        if (y > 1) // This converts y to variable z.  z accounts for the array going from 0 - 11 
                z = (y - 2);//  rather than 1 - 12 and represents the previous month number in the array currentRain
        else if (y == 1)
                z = 11;
        else
                z = 10;

        outStream << "Please enter the amount of rain (to the nearest inch) that fell " << endl;
        outStream << "last month.  Then enter the amount that fell the month before " << endl;
        outStream << "that.  Continue until you have entered an amount for the last 12 " << endl;
        outStream << "months.  Press enter after every measurement." << endl;

        int m = 0;

        while (m < 12) // m is used to make sure the while statement is executed exactly 12 times
        {
                if (z > 0)
                {
                        inStream >> r; // r is the last recorded rain measurement for any month z
                        outStream << endl;
                        currentRain[z] = r;
                        z--;
                }
                else
                {
                        inStream >> r;
                        outStream << endl;
                        currentRain[0] = r;
                        z = 11;
                }
                m++;
        }

        char results = 'g'; // results is the variable that determines how the data is represented
        outStream << endl; // and it is initialized to g (graph)

        while ((results == 'g') || (results == 'G') || (results == 'c') || (results == 'C'))
        {
                outStream << "Enter g to see the results graphically or c to see a chart. Or press any " << endl;
                outStream << "other key to quit." << endl << endl << endl;

                inStream >> results;

                if ((results == 'c') || (results == 'C'))
                {
                        outStream << "Month__Average Rainfall__Previous Recorded Rainfall__PRF Deviation From Average" << endl;
                       
                        x = 0;

                        while (x < 12)
                        {
                                outStream << x + 1;
                                outStream << "          ";
                                outStream << avgRain[x];
                                outStream << "                      ";
                                outStream << currentRain[x];
                                outStream << "                            ";
                                outStream << currentRain[x] - avgRain[x] << endl;

                                x++;
                               
                        }
                }
        if ((results == 'g') || (results == 'G'))
        {
                outStream << endl << endl << endl;

                x = 0;

                while ((x < 12) && (x >= 0))
                {
                        outStream << (x + 1) << " ";
                       
                        int g = avgRain[x]; // g is initialized to the value of any given x index in
                        while (g > 0) // the avgRain array
                        {
                                outStream << "*";
                                g--;
                        }
                        outStream << endl;
                        outStream << (x + 1) << " ";
                        int h = currentRain[x]; // h is similar to g except used for the currentRain array
                        while (h > 0)
                        {
                                outStream << "*";
                                h--;
                        }
                        outStream << endl << endl;
                        x++;
                       
                }
                        outStream << "The top line indicates the average rainfall; bottom indicates the last " << endl;
                        outStream << "recorded measure for that month.  Every * represents 1 inch." << endl << endl << endl;
        }
        }
        inStream.close();
        outStream.close();
}
2008 scandalz.net
Oh, I am a C programmer and I'm okay I muck with indices and structs all day And when it works, I shout hoo-ray Oh, I am a C programmer and I'm okay
CountryUS
IP Address38.107.191.98
User AgentCCBot/1.0 (+http://www.commoncrawl.org/bot.html)