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.

error C2228: left of '.Text' must have class/struct/union

by phohammer at 20:18 PM, 02/08/2010

I am attempting to create a GUI for a console C++ program in Visual C++. Apparently, it is like learning the language all over. Here is my problem:

I am attempting to write the contents of a textbox to a file, but I get the error "error C2228: left of '.Text' must have class/struct/union".

Here is my problem spot, i think:

private: System::Void addtxt_Click(System::Object^  sender, System::EventArgs^  e) {
                                std::ofstream fout;
                                fout.open("callie.txt");
                                        fout<<txtbox.Text;
                                fout.close();
                        }

However, the entire source code is here, if you want to look: http://powermite.pastebin.com/f70e98790

It compiles and runs fine if I try to write a set string to the file, such as "Hello", but it won't take the contents of the text box...

I have searched and read nearly everything I could find on the error on Google, but it seems as though it is a different fix every time, none of which really apply to my situation.

Thanks in advance for any help!

hex2int problems

by cwarn23 at 20:10 PM, 02/08/2010

Hi and I have a hex to int function but it isn't converting the hex to integers properly. Below is the code an example is the hex bb76e739 which should = 3145131833 but with the function it equals 2147483647. I heard sprintf or something like that can convert the hex to int and assign it to a variable but have no code for it. Below is my current function which doesn't always work.
long hex2int(const std::string& hexStr) {
  char *offset;

  if (hexStr.length( ) > 2) {
    if (hexStr[0] == '0' && hexStr[1] == 'x') {
      return strtol(hexStr.c_str( ), &offset, 0);
    }else{
                std::string str="0x";
                str.append(hexStr);
                return strtol(str.c_str( ), &offset, 0);
    }
  }
}
Can anybody suggest a better function where the input is a std::string because this is causing all sorts of troubles?
Edit: I'm using C++ with VC++

Dynamic Memory 2d Array

by scott6480 at 19:54 PM, 02/08/2010

In my assignment I am supposed to use a pointer to create a 2-D array dynamically. Initialize each element in the array to the sum of its row and column. Then display each element of the array on the console.

I have the program written and it works except for the part that says initialize each element in the array to the sum of its row and column.

For the life of me I cannot wrap my head around how to do that. Can anyone give me a little help or suggestion as to a best method. I have set it to initialize everything to zero at the moment.

I tried doing this with no success
for (int j=0;j<5;j++) //initalize array elements to sum of row and column
        {
                for (int i=0;i<5;i++)
                        p[i][j]=i+2;

        }

//Scott 
// Homework Chapter 14A



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

#define frz system("pause");

using namespace std;


int main()
{
        int **p;

        p=new int* [5];//creates 2 rows
       
       
        for(int row=0;row<5;row++)//creates 2 columns
                p[row]=new int[5];

       
        cout<<"Base address of memory pointer: "<<p<<endl;


        for (int j=0;j<5;j++) //initalize array elements to sum of row and column
        {
                for (int i=0;i<5;i++)
                        p[i][j]=0;

        }

        for (int j=0;j<5;j++)
        {
                for (int i=0;i<5;i++)
                        cout<<setw(5)<<p[i][j];
                cout<<endl;

        }



       
        cout<<endl;
        p=NULL;
        delete [5] p; //deallocate dynamic memory
        cout<<"Base address of memory pointer: "<<p<<endl;
        cout<<endl;

        frz;
        return 0;
}

What's wrong here?

by halluc1nati0n at 19:47 PM, 02/08/2010

Tried this on my UNIX box.. Why aren't the array contents being stored/displayed ??

#include <iostream>
#include <fstream>
#include <unistd.h>
#include <sys/signal.h>

using namespace std;

int main(int argc, char *argv[])
{
    int pid;
        pid_t  pid_chk;
        int pid_array[2];
        int count[25], length, i, j;


        for (i=0; i<3; i++) {
                pid_array[i] = 0;
        }       
       
        for (i=0; i<3; i++) {

                for (j=0; j<=25; j++)
                        count[j]=0;
                //fork();
                if ((pid=fork())==0) {
                        /* child code */
                        // Store the PID of newly created child in an array.
                        pid_chk = getpid();
                        cout << "My process id is : " << pid_chk << endl;
                        cout << "Value of i is : " << i << endl;
                        pid_array[i] = pid_chk;
                        cout << "Value of pid_array is : " << pid_array[i] << endl;
                        //break;
                        kill(pid_chk, SIGKILL);
                }
                else {
                        // Parent's code
                        // Do nothing
                }
        }
               
        for (i=0; i<3; i++) {
                cout << pid_array[i] << endl;
        }       
    return 0;
}


Output :

{linux0:~/proj} trial_suggestion
My process id is : 10106
Value of i is : 0
Value of pid_array is : 10106
My process id is : 10107
Value of i is : 1
Value of pid_array is : 10107
My process id is : 10108
Value of i is : 2
Value of pid_array is : 10108
0
0
0

String Output

by heredia21 at 19:13 PM, 02/08/2010

int main()
{ string s = "12a34b56c78d";
  int size = 12;
  writeStuff(s,size);
  return 0;
} // end main
void writeStuff(string s, int size)
{    if (size > 0)
    {    cout << s.substr(size-1, 1);
            writeStuff(s, size-3); 
      }  // end if
}  // end writeStuff

What is supposed to be the output of this?

Recursive

by heredia21 at 19:12 PM, 02/08/2010

[code]int main()
{
recurse(5,3);
return 0;
} // end main
void recurse(int x, int y)
{ if (y > 0)
{ ++x;
--y;
cout << x << " " << y << endl;
recurse(x, y);
cout << x << " " << y << endl;
} // end if
} // end recurse[/code/
What is the output?

C++ help

by heredia21 at 19:10 PM, 02/08/2010

#include <iostream>
using namespace std;



int num, factorial;
num = 6;
factorial = Fact(num);
cout << num << "! = "
<< factorial;
return 0;
} // end main
int Fact (int num)
{ if (num == 0)
return 1;
else
return num*Fact(num-1);
} //end Fact
int main()

What is the output?

keep track of items purchased

by timbomo at 18:20 PM, 02/08/2010

ok how will i keep track of the items i bought? i have not the slightest clue on that. i dont even know where to start.
can someone point me in the right direction?

#include<iostream>
 using namespace std;
 int main()
 {
        char symb;
        int item_purch, numb_item_purch, quit,;
        double mug = 2.50f, teeshirt = 9.50f, pen= 0.75f,tot_mon = 30.0f;

        cout << "You have 30 dollars to spend.\n";
    do
        {
            cout << endl;
            cout << "What do you want to buy today?\n";


            cout << " A) Mugs $2.50 " << endl;
            cout << " B) teeshirt $9.50 " << endl;
            cout << " C) Pens .75 cents " << endl;
            cout << " D) Quit" << endl;
            cout << " Enter your letter and press Return when finished" << endl;
            cin >> symb;

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


        switch (symb)
        {
            case 'A':;
            case 'a':;
            cout << " You have choosen A) mugs for $2.50 \n" << endl;
            tot_mon -= mug;
            cout << " You have " << tot_mon << " remaining \n" << endl;


            break;
            case 'B':;
            case 'b':;
            cout << " You have choosen B) teeshirt for $9.50 " << endl;
            tot_mon -= teeshirt;
            cout << " You have " << tot_mon << " remaining \n " << endl;

            break;

            case 'C':;
            case 'c':;
            cout << " You have choosen C) Pens for .75 cents " << endl;
            tot_mon -= pen;
            cout << " You have " << tot_mon << " remaining \n " << endl;

            break;

            case 'D':;
            case 'd':;
            cout << " You have choosen D) which means you want to Quit" << endl;
            tot_mon = 0;
            break;

            default:
            cout << "Input error. Select again" << endl;

        }

        if ( tot_mon == 0.0f )
                  cout << "You need more cash, you dont have enough\n" << endl;

        else

            cout << " Would you like anothe purchase, please choose another letter.\n" << endl;


        } while ( tot_mon >= 0.0f );
        {
            cout << "Thank you for shopping.\n";
        }
    return 0;
 }

LeftClick & RightClick on mouseDownEvent

by Lukezzz at 17:05 PM, 02/08/2010

I use a panel and if the user Leftclicks an area with the mouse, I am trying to set the variable LeftRightClick to "Left" and the same for rightclick, "Right".

Then I call the button43_MouseDown event to show the correct MessageBox, depending on if it was a leftClick or RightClick.

When doing this the messageBox: MessageBox:: Show("LeftClick");
is always shown even that a rightclick was made.

I wonder why this is happening ?
String^ LeftRightClick; //Global Variable

private: System::Void panel1_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
{
        if( e->Button == System::Windows::Forms::MouseButtons::Left )
        {
                if( e->X >= 304 && e->X <= 346 && e->Y >= 369 && e->Y <= 392 )
                {
                        LeftRightClick = "Left";
                }
        }
        if( e->Button == System::Windows::Forms::MouseButtons::Right )
        {
                if( e->X >= 304 && e->X <= 346 && e->Y >= 369 && e->Y <= 392 )
                {
                        LeftRightClick = "Right";
                }
        }
        button43_MouseDown(nullptr, nullptr);
}







private: System::Void button43_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
{
        if( LeftRightClick == "Left" )
        {
                MessageBox::Show("LeftClick");
        }
        if( LeftRightClick == "Right" )
        {
                MessageBox::Show("RightClick");
        }
}

Array passing problem

by nsjoe at 16:53 PM, 02/08/2010

Can someone quickly point out what the problem is here? I'm sure it's something small but I've been coding for too long to see it.

The problem is that in the balance method call, the first parameter is an array. if I hard code a test array, or if I create a test pointer array and fill it, the program works fine, but if I pass the pointer as I am here, I get output problems. To much detail to get into now but I'm sure it's something to do with these array pointers I'm messing with. I think the pointer is somehow being passed in as empty or as a single value, in stead of a whole list of values. I'm still new at pointers so be easy on me.

        this->wordArrayLength++;
        string* tempArray = new string[this->wordArrayLength + 1];
       
        tempArray[0] = inWord;
        tempArray[this->wordArrayLength] = '\0';
       
        for (int i = 0; i < this->wordArrayLength; i++ ) {
                tempArray[i+1] = this->wordArray[i];
                cout << tempArray[i] << endl;
        }
       
        int counter = 0;
        for (int i = this->wordArrayLength -1; i > -1; i-- ) {
                this->wordArray[counter] = tempArray[i];
                counter++;
        }       
       
        for (int i = 0; i < this->wordArrayLength; i++ ) {
                tempArray[i] = this->wordArray[i];
                //cout << tempArray[i] << endl;
        }       

        delete []wordArray;
        this->wordArray = tempArray;
       
        int* levelNums = new int[2];  //create new array to hold tree level index numbers - starts at 1 (1st level)
        levelNums[1] = '\0';
        int levelNumsLength = 1;

        balance(this->wordArray, wordArrayLength, wordArrayLength, 1, levelNums, levelNumsLength);

tracking looping

by timbomo at 16:50 PM, 02/08/2010

How would i keep track of money spent? and items bought when i loop and how do i say i want multiple items meaning if i want to purchase more than one teeshirt or mug.


 
/* SIUE's bookstore is having aspecail sale on tiems embossed with the cougar logo. For a limited time, three items, mugs, teeshirts, and pens
 are offered at a reduced rate with tax included to simplify the sales. Mugs are going for $2.50, teeshirts for $9.50 and pens for 75
 cents. Coincidentally, your parents (or spouse, friend, coworker, or other person you know off-campus) just gave you $30.00 to buy SIUE
 stuff for them.*/

 #include<iostream>
 using namespace std;
 int main()
 {
    char symb;
    int item_purch, numb_item_purch, quit, answ;
    double mug, teeshirt, pen, tot_mon, curr_cash, mon_spent;

    cout << "You have 30 dollars to spend.\n";
    do
    {
        cout << endl;
    cout << "What do you want to buy today?\n";
     tot_mon = 30;

            cout << " A) Mugs $2.50 " << endl;
            cout << " B) teeshirt $9.50 " << endl;
            cout << " C) Pens .75 cents " << endl;
            cout << " D) Quit" << endl;
            cout << " Enter your letter and press Return when finished" << endl;
            cin >> symb;

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


   
     switch (symb)
        {
            case 'A':;
            case 'a':;
            cout << " You have choosen A) mugs for $2.50 \n" << endl;
            mug = 2.50;
            curr_cash = tot_mon - mug;
            cout << " You have " << curr_cash << " remaining \n " << endl;
            tot_mon = 30;

            break;
            case 'B':;
            case 'b':;
            cout << " You have choosen B) teeshirt for $9.50 " << endl;
            teeshirt = 9.50;
            curr_cash = tot_mon - teeshirt;
            cout << " You have " << curr_cash << " remaining \n " << endl;
            tot_mon = 30;
            break;

            case 'C':;
            case 'c':;
            cout << " You have choosen C) Pens for .75 cents " << endl;
            pen = .75;
            curr_cash = tot_mon - pen;
            cout << " You have " << curr_cash << " remaining \n " << endl;
            tot_mon = 30;
            break;

            case 'D':;
            case 'd':;
            cout << " You have choosen D) which means you want to Quit" << endl;
            quit = 0;
            break;

            default:
            cout << "Input error. Select again" << endl;
        }
        if ( curr_cash = 0)
        {
            cout << "You need more cash, you dont have enough\n" << endl;
            curr_cash = tot_mon - mon_spent;
        }
        else
        {
            cout << " Would you like anothe purchase, please choose another letter.\n" << endl;

                            }
        } while ( curr_cash <= 0);
     
        cout << "Thank you for shopping.\n";
    return 0;
 }

error C2955 when using list

by mrackley86 at 16:08 PM, 02/08/2010

New to templates and lists but i have to use them for a class project. I got it working in one file then i tried to make it a class and I keep getting this error:

1>c:\users\r4ck13y\programming\c++ projects\project2.1\project2.1\merginglists.h(11) : error C2955: 'std::list' : use of class template requires template argument list
1> c:\program files\microsoft visual studio 9.0\vc\include\list(95) : see declaration of 'std::list'

Here is the header file that im about 90% sure the error is coming from. Please help. Thank you.

[code c++] #ifndef MERGINGLISTS
#define MERGINGLISTS
#include "stdafx.h"
#include <list>
#include <iostream>
using namespace std;
class MergingLists : public list
{
public:
MergingLists();
template <typename T> void splitlist(list<T> L, list<T>& first, list<T>& second);
template <typename T> list<T> merge(list<T>& first, list<T>& second);
template <typename T> list<T> mergesort(list<T>& L);
};
#endif [/code]

Identify MouseClick location in panel

by Lukezzz at 15:54 PM, 02/08/2010

I have a panel called panel1.

What I wonder how it is possible to do is that when you click the mouse on the location 304,369 in the panel, I want to display a messageBox.

How would that be possible to identify the location in code ?
private: System::Void panel1_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) 
{

if( ??? )
{
    MessageBox::Show("You clicked Location 304,369 in the panel 
                                      with the mouse !");

}

}

String Selection Sort with files

by db132074 at 15:14 PM, 02/08/2010

Hi, I'm having a problem with displaying names from a text file. I'm passing the names from the text file to an array that will be sorted, but I'm not getting the names to show like I want them to.

It should display the different names as Last, First

But it comes up as
Last,
First

I believe that I'm not passing the names from the text file to the array properly, but I'm not sure what I should do.

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

//function prototypes
void selectionSort(string[], int);
void showArray(string[], int);

int main()
{
    //Input file stream object
    ifstream inputFile;   
    //constant for number of names
    const int NUM_NAMES = 20;     
    //array that holds names   
    string names[NUM_NAMES];   
    //open the file
    inputFile.open("namesFile.txt");
   
    // Read names from file into array
    for(int count = 0; count < NUM_NAMES; count++)
        inputFile >> names[count];
                 
    //close file
    inputFile.close();
                               
    cout<<"Unsorted names :\n\n";
   
    //show and then sort names                         
    showArray( names, NUM_NAMES );
    selectionSort( names, NUM_NAMES );
   
    //clear screen for readablity
    system("cls");
   
    //show sorted names
    cout<<"Sorted names :\n\n";
   
    showArray( names, NUM_NAMES );
                                 
    return 0;
}

I'm not looking for someone to do my homework for me, I just need a push in the right direction.

Is Visual C++ (ver8) Broken

by walter clark at 14:26 PM, 02/08/2010

Is there anyone out there that finds Visual C++ (ver8) Debugger broken? Specifically with regard to variables out of scope.

I have asked here about specific problems and none of the proposed solutions work. The debugger works on the easiest of things, but half the time, things that are obviously in scope, it complains that they aren't.
The only people who respond, obviously the debugger works for them and I appreciate their advice. But let me see if there's anyone else that has to spend half the day displaying variables with code because the debugger won't.

Walt

error trap and statement problems

by timbomo at 13:37 PM, 02/08/2010


Did i use the code tag correctly ? let me know?

Im trying to figure out how to error trap this program so if the user doesnt put in a valid response then a message will cum up and they will go back 2 the beginning until they do it correctly.

also i want to subtract the money they spend and tell them their remaining amount, also i want to keep track of the number of items they purchase.

when i do it all that comes up is a whole bunch of numbers.
can anyone help when you compile this program i want this format but the numbers arent right

can anyone help?

/* SIUE's bookstore is having aspecail sale on tiems embossed with the cougar logo. For a limited time, three items, mugs, teeshirts, and pens
are offered at a reduced rate with tax included to simplify the sales. Mugs are going for $2.50, teeshirts for $9.50 and pens for 75
cents. Coincidentally, your parents (or spouse, friend, coworker, or other person you know off-campus) just gave you $30.00 to buy SIUE
stuff for them.*/

#include<iostream>
using namespace std;
int main()
{
char symb;
int item_purch, numb_item_purch, quit;
double mug, teeshirt, pen, tot_mon, curr_cash, mon_spent;

cout << "What do you want to buy today?\n";
cout << "You have 30 dollars to spend.\n";


cout << " A) Mugs $2.50 " << endl;
cout << " B) teeshirt $9.50 " << endl;
cout << " C) Pens .75 cents " << endl;
cout << " D) Quit" << endl;
cout << " Enter your letter and press Return when finished" << endl;
cin >> symb;


switch (symb)
{
case 'A':;
case 'a':;
cout << " You have choosen A) mugs for $2.50 \n";
mug = 2.50;
cout << " You have " << curr_cash << " remaining \n ";
tot_mon = 30;
curr_cash = tot_mon - mug;
cout << " You have purchased " << numb_item_purch << " today \n ";
numb_item_purch = item_purch + 1;
break;
case 'B':;
case 'b':;
cout << " You have choosen B) teeshirt for $9.50 ";
teeshirt = 9.50;
break;
case 'C':;
case 'c':;
cout << " You have choosen C) Pens for .75 cents ";
pen = .75;
break;
case 'D':;
case 'd':;
cout << " You have choosen D) which means you want to Quit" << endl;
quit = 0;
break;
}



cin >> tot_mon;
curr_cash = tot_mon - mon_spent;
cin >> curr_cash;
cin >> mon_spent;




return 0;
}
I'm writing a C++ program in which I need to display the bits that represent both a 32-bit and 64-bit floating point number. I had no problem properly displaying the 32-bit number, but I'm having trouble with the 64-bit number.

This is the code that I'm trying to use:
        unsigned int* low = (unsigned int*)&doubleValue;
        unsigned int* high = (unsigned int*)((&doubleValue)+4);
        unsigned int mask = 0x80000000; // 1000 0000 0000 0000
        unsigned int result;

        for(int i = 31; i>=0; i--)
        {
                result = (*high & mask) >> i;
                mask = mask >> 1;
                cout << result;
        }
        mask = 0x80000000;
        for(int i = 31; i>=0; i--)
        {
                result = (*low & mask) >> i;
                mask = mask >> 1;
                cout << result;
        }

The variable 'doubleValue' is of type double and holds the number that I am trying to display in binary. I can get the lowest 32 bits to display correctly, its the highest 32 bits that I'm having trouble with.

Any help is greatly appreciated!

error trap, and some more basics

by timbomo at 12:59 PM, 02/08/2010

Im trying to figure out how to error trap this program so if the user doesnt put in a valid response then a message will cum up and they will go back 2 the beginning until they do it correctly.

also i want to subtract the money they spend and tell them their remaining amount, also i want to keep track of the number of items they purchase.

when i do it all that comes up is a whole bunch of numbers.
can anyone help when you compile this program i want this format but the numbers arent right

can anyone help?

/* SIUE's bookstore is having aspecail sale on tiems embossed with the cougar logo. For a limited time, three items, mugs, teeshirts, and pens
are offered at a reduced rate with tax included to simplify the sales. Mugs are going for $2.50, teeshirts for $9.50 and pens for 75
cents. Coincidentally, your parents (or spouse, friend, coworker, or other person you know off-campus) just gave you $30.00 to buy SIUE
stuff for them.*/

#include<iostream>
using namespace std;
int main()
{
char symb;
int item_purch, numb_item_purch, quit;
double mug, teeshirt, pen, tot_mon, curr_cash, mon_spent;

cout << "What do you want to buy today?\n";
cout << "You have 30 dollars to spend.\n";


cout << " A) Mugs $2.50 " << endl;
cout << " B) teeshirt $9.50 " << endl;
cout << " C) Pens .75 cents " << endl;
cout << " D) Quit" << endl;
cout << " Enter your letter and press Return when finished" << endl;
cin >> symb;


switch (symb)
{
case 'A':;
case 'a':;
cout << " You have choosen A) mugs for $2.50 \n";
mug = 2.50;
cout << " You have " << curr_cash << " remaining \n ";
tot_mon = 30;
curr_cash = tot_mon - mug;
cout << " You have purchased " << numb_item_purch << " today \n ";
numb_item_purch = item_purch + 1;
break;
case 'B':;
case 'b':;
cout << " You have choosen B) teeshirt for $9.50 ";
teeshirt = 9.50;
break;
case 'C':;
case 'c':;
cout << " You have choosen C) Pens for .75 cents ";
pen = .75;
break;
case 'D':;
case 'd':;
cout << " You have choosen D) which means you want to Quit" << endl;
quit = 0;
break;
}



cin >> tot_mon;
curr_cash = tot_mon - mon_spent;
cin >> curr_cash;
cin >> mon_spent;




return 0;
}

some collision detection help please

by nola_Coder at 12:13 PM, 02/08/2010

I am making a pong-like game for a class.
I am having trouble with the ball's collision detection.

The game is a 1 player version, where the ball and paddle are both contained in a box. The player uses a gun which is built into the paddle, in order to shoot a hole through the back wall so that the ball may escape (earning them a point)
I have also given the paddle 2-D movement, instead of just along the x-axis.

The ball seems to be bouncing off the side walls fine, but when it hits the top wall, it seems to "reset" the ball, and it just reappears near the paddle and starts moving again.
I also notice that when the ball is reflected off a wall toward the paddle, it seems to be attracted to the paddle like a magnet.

I tried to post my code, but it was giving me some error about "you do not have permission to create tags" or something like that.

I am wondering if there is a way to detect collision, based off of getpixel(), but for more than one pixel at a time. For example, since the ball is circular, instead of just testing one pixel in the direction that the ball is going, is it possible to getpixel() for a specific area of pixels instead of just one single pixel at a time? Does my question make sense?

Please help!
Thank you!!

drawing a rectangle

by corby at 11:47 AM, 02/08/2010

i need help creating a rectangle where the user creates the border and fills in the empty space with any symbol they want.

it should look like this

#######
#@@@@#
#@@@@#
#@@@@#
#######

mine only looks like this

#
@@@@@
#
@@@@@
#
@@@@@

any help??? heres my code:




char b;// character used to draw border of rectangle
char f;//character used to fill the rectangle
cout << "What character would you like to use to draw the border of your rectangle?";
cin >> b;
cout << "What character would you like to use to fill the rectangle?";
cin >> f;
for (int i = 0; i < rectangleLength; i++)
{
cout << b;
cout <<"\n";

for (int j = 0; j < rectangleWidth; j++)
{
cout << f;
}
cout << "\n";

Legitimate dates using the assert function

by deetlej1 at 11:25 AM, 02/08/2010

Hi There,

I need assistance with the assert function. The question is convert a date to Julian date and then check which one is the smallest and subtract to show the different days. That is all done. The part I have no idea is how to use the assert function to verify that the dates entered are legitimate dates.

Is there someone that can assist me please.

//Converting date to Julian format

#include <iostream>
#include <assert.h>

using namespace std;

//definition for the number of days in
//each month
int daysPerMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int calcJulian(int dd, int mm)
{
    int t = 0;
    int numDays;
   
    for (int i = 1; i < mm; i++)
    {
        switch(i)
        {
                case 1: numDays = daysPerMonth[0];
                case 3: numDays = daysPerMonth[2];
                case 5: numDays = daysPerMonth[4];
                case 7: numDays = daysPerMonth[6];
                case 8: numDays = daysPerMonth[7];
                case 10: numDays = daysPerMonth[9];
                case 12: numDays = daysPerMonth[11];
                      t += 31;
                      break;
               
                case 4: numDays = daysPerMonth[3];
                case 6: numDays = daysPerMonth[5];
                case 9: numDays = daysPerMonth[8];
                case 11: numDays = daysPerMonth[10];
                      t += 30;
                      break;
                   
                case 2: numDays = daysPerMonth[1];
                      t += 28;
                      break;                                           
        }
    }
    t += dd;
    return t;
}

int main()
{
    int dd, mm;
     
    cout << "Enter day (dd)" << endl;
    cin >> dd;
    cout << "Enter month (mm)" << endl;
    cin >> mm;
   
    int f = calcJulian(dd, mm);
   
    int dd2, mm2;
    cout << "Enter day (dd)" << endl;
    cin >> dd2;
    cout << "Enter month (mm)" << endl;
    cin >> mm2;
   
    int g = calcJulian(dd2, mm2);
    cout << "Julian day: " << f << endl;
    cout << "Julian day: " << g << endl;
   
    //check which is the smaller date and then subtract
    //to get the different between the days
    float ans;   
    if ( f < g ) {
        ans = (g-f);
    }
    else {
        ans =(f-g);
    }       

    cout << "Numbers of days different between the two days is: " << ans << endl;
   
    system("PAUSE");
    return 0;
}

Event Handling

by IDSTECH at 10:14 AM, 02/08/2010

I am very new to C++ and would like to know how to handle the following:

Let's say I have a button on a form. When the user clicks the button, a new textbox is created on the form. How can I add event handling for this new text box?

Regards
EM

create a menu

by timbomo at 10:03 AM, 02/08/2010

How can i make this into a menu where you select a letter and you get a response that reads

you have choosen "a" which is $2.50


/* SIUE's bookstore is having aspecail sale on tiems embossed with the cougar logo. For a limited time, three items, mugs, teeshirts, and pens
are offered at a reduced rate with tax included to simplify the sales. Mugs are going for $2.50, teeshirts for $9.50 and pens for 75
cents. Coincidentally, your parents (or spouse, friend, coworker, or other person you know off-campus) just gave you $30.00 to buy SIUE
stuff for them.*/

#include<iostream>
using namespace std;
int main()
{
char symb,symb1, symb2, symb3;
int item_purch, numb_item_purch, quit;
double mug, teeshirt, pen, tot_mon, curr_cash, mon_spent;

cout << "What do you want to buy today?\n";



cout << " A) Mugs $2.50 " << endl;
cout << " B) teeshirt $9.50 " << endl;
cout << " C) Pens .75 cents " << endl;
cout << " D) Quit" << endl;
cout << " Enter your letter and press Return when finished" << endl;
cin >> mug;
cin >> teeshirt;
cin >> pen;
cin >> quit;
mug = ('A' || 'a');
teeshirt = ('B' || 'b');
pen = ('C' || 'c');
{
if ((mug == 'A') || (mug == 'a'))
{

mug = 2.50;
}
else if ((teeshirt == 'B') || (teeshirt == 'b'))
{

teeshirt = ('B' || 'b');
}
else
{
cout << "Wrong select a letter" << endl;
}
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

switch (symb)
{
case 'A':
cout << " A) Mugs $2.50 ";
mug = 2.50;
break;
case 'B':
cout << " B) teeshirt $9.50 ";
teeshirt = 9.50;
break;
case 'C':
cout << " C) Pens .75 cents ";
pen = .75;
break;
case 'D':
cout << " D) Quit" << endl;
quit = 0;
break;
}



return 0;
}

Using C library with anonymous struct in C++

by nkinar at 09:44 AM, 02/08/2010

Hello--

I've been writing some code in C++ to test the tffs-lib library, which is written in C. The library provides functions for directly accessing a FAT file system from within a program. Although most modern operating systems have drivers for accessing the FAT filesystem on SD cards, I am working with an embedded Linux system, and I would like to directly access the FAT filesystem using a device node (/dev/mmcblk1p1) to speed up write I/O access.

I am able to build the tffs-lib and statically link it with my test program. My cross-compiler build is based on gcc 4.2.2.

However, I receive the following error when compiling the code. This error mentions an "anonymous struct," which I believe is not legal in C++.

request for member 'fatsz' in 'htffs', which is of non-class type '<anonymous struct>*'        test.cpp test-tffs-lib

Is it possible to use an anonymous struct in C++, even when the anonymous struct is being used within a C library? I tried passing the command-line switch "-features=extensions" to gcc, but (strangely enough) this results in no executable being created. However, after passing this switch, there is no warning generated, and the code compiles cleanly (without the output executable being created.)

Here is the code of my very simple test program in C++. The error occurs on line 32 below.


#include <iostream>
#include <string>

// TFFS library include (for C code)
extern "C" {
#include <tffs.h>
}

void doTest();

int main()
{
        doTest();
return 0;
}

void doTest()
{
        int32_t ret;
        std::string sd_dev = "/dev/mmcblk1p1";
        tffs_handle_t htffs;

        //  mount the filesystem directory
        ret = TFFS_mount((byte*)sd_dev.c_str(), &htffs);
        if(ret != TFFS_OK)
                exit(1);

        // check the space available on the medium

        // This is the line of code where the error occurs
        uint32_t fatsz = htffs.fatsz;
        std::cout << "fatsz = " << fatsz << std::endl;

        // unmount the filesystem directory
        ret = TFFS_umount(htffs);
        if(ret != TFFS_OK)
                exit(1);
}

function

by vipin_98 at 09:00 AM, 02/08/2010

which function is used to increase the font size in c++ program

header file problem...

by TheGhost at 07:07 AM, 02/08/2010

my code includes this function

void read(set<string> &mySet);

but when i put this line in the header file, i get the following errors:

error: variable or field 'read' declared void
error: 'set' was not declared in this scope
error: 'string' was not declared in this scope
error: 'mySet' was not declared in this scope

so, what should i write to make this thing work?

thanks.

char() and int() not working the same

by Begjinner at 06:49 AM, 02/08/2010

When you use char(130) you get the é. When you do int('é') you get -23... and with my program to get value it is -126...

How on earth can I get the 130 value when entering the é ?

Thanks for looking.

With this program I printed out the letter list with number:
#include <iostream> 
using namespace std;
int main() {

for(int i=0; i<255;i++){
        cout << char(i) << " " << i << '\n';
        };
        system("pause"); //not safe
        return 0;
}

With this program I enter a letter and it gives me the value.
#include <iostream> 
using namespace std;
int main() {

label:
        char i;
        cin >> i;
        int temp;
        temp = int(i);
        cout << temp ;
        cout << '\n';
goto label;

        system("pause"); //not safe
        return 0;
}

Can I increament the Space?

by khevz09 at 06:37 AM, 02/08/2010

My only problem is the spacing..... to make it right.... i need to make it inverted pyramid pattern...
like this:

9 8 7 6 5 4 3 2 1
 9 8 7 6 5 4 3 2
  9 8 7 6 5 4 3
  9 8 7 6 5 4
    9 8 7 6 5
    9 8 7 6
      9 8 7
      9 8
        9

#include <iostream.h>
#include <string.h>
#include <conio.h>
main()
{
clrscr();
        int num,n;
        cout<<"enter:";
        cin>>n;
        num=0;
        while (num !=n)
        {
        for(int i = n; i >  num;--i)
                {
                cout << " " << i;
                }
        cout << endl<<"  ";
        if(num == 0)
        cout<<" ";
        ++num;
        }
        getch();
}

this is my code and only thing that wrong is the spacing before the rows...

Draw path with variables

by yin1031 at 04:37 AM, 02/08/2010

Hi there
I want to use c++ to draw a path
The path is based on two variables, x and y
and x and y will change automatically every second

So I think the flow should be like this:
t=0, (x,y)=(0,0) ->draw a point on the graph
t=1, (x,y)=(2,2)->draw another point on the graph
....
repeat the above steps until the user stop the program.

But I have no idea how can I ask the program to draw point every second and keep all the points in the graph? I tried to use a timer
private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e)          
                {                  ShowGraphics=true;        }
so when ShowGraphics is true,
        if (IsShowGraphics==false)
                return;
       
        Color Black=Color::FromArgb(250, Color::Black);
       
        SolidBrush^ Brush_A = gcnew SolidBrush( Black );

        if (x!=0 && y!=0)
        {                CallerGDI->FillRectangle(Brush_A,x,y,10,10); //draw point
                IsShowGraphics=false;
        }

But the program only draws one point at each time AND replaces the previous one. How can I keep the "old" points in the graph?

Thanks for yr time, I really appreciate your help~

displaying files

by anthony5557 at 04:05 AM, 02/08/2010

I wonder if anyone can help me. I'm suppose to write a program to ask the user to enter the file they want to display and display the file they want 24 lines at a time. It pauses at 24 and asks them to press enter and displays the next 24 lines. I have a pretty good code I think for a beginner, but no matter what file I enter when I test the program it goes to the error checker and says it couldn't open the file. I will attach my code. If anyone has any tips I would appreciate it. Thanks.

//This program will write to a file and then
//ask the user to recall that file and display.
#include <iostream>
#include <fstream>
using namespace std;

//Constant for array size
const int SIZE = 100;

int main()
{
        char MyFile[SIZE];  //Hold the file name
        char inputLine[SIZE];    //To hold the line of input
        fstream address;  //File stream object
        int line = 0;      //Line counter
        char ch;            //To hold a character

        address.open("address.txt", ios::out);
        address<<"Anthony Smith "<< endl;
        address.close();


        //Get the file name.
        cout<< " Enter the name of the file you are";
        cout<< " interested in.\n";
        cout<<" ";cin.getline(MyFile, SIZE);

        //Open the file.
        address.open(MyFile);

        //Test for errors
        if(!address)
        {
                cout<<" There was an error opening "<< MyFile << endl;
                exit(EXIT_FAILURE);
        }
        else;
        {
                address.get(ch);
        }

        //Read the contents of file and display
        while(!address.eof())
        {
                //Get a line from the file.
                address.getline(inputLine,SIZE,'\n');


                //Display the line.
                cout<< inputLine << endl;

                //Update line counter
                line++;

                //Display 24 lines at a time.
                if(line == 24)
                {
                        cout<< " Press enter to continue.\n";
                        cin.get();
                        line = 0;
                }
        }

        //Close file.
        address.close();
        return 0;
}
Hi,
I'm able to write a copy constructor for a class which contains pointer as a data member. However, when I have a reference as a data member, the copy constructor does not help, i.e. when I change that member for one object, the change is reflected in another one also.
Please refer to the code below.

class Student {
        private:
                int roll_no;
                char *pname;
                int & marks;

        public:
                Student():marks(a)      {
                        roll_no = 0;
                        pname = new char[7];
                        strcpy(pname, "no one");
                }

                Student(int a, char *p, int &m):marks(m)
                {
                        roll_no = a;
                        pname = new char [strlen(p) + 1];
                        strcpy(pname,
                }

                Student(const Student &ob): marks(ob.marks)
                {
                        cout << "TRACE: in copy con" << endl;
                        roll_no = ob.roll_no;
                        pname = new char[strlen(ob.pname)+1];
                        strcpy(pname, ob.pname);
                }
                void change_data(int num, char *str, int n)
                {
                        roll_no = num;
                        strcpy(pname,str);
                        marks = n;
                }
                void show_data();
};

int main()
{
        int a = 102;

        Student Ajay(1, "Ajay",a) ;
        Student s1 = Ajay;

        Ajay.show_data();      // 1 Ajay 102
        s1.show_data();        // 1 Ajay  102

        a = 1122;
        s1.change_data(12,"Roshan",a);

        Ajay.show_data();      // 1 Ajay 1122
        s1.show_data();        // 12 Roshan 1122
        return 0;
}

now the question is, how to avoid this reflection of values in both the objects?

Acces violation using char*

by elexender at 03:24 AM, 02/08/2010

Hi,

Im pretty new to c++ programming so plz dont be offended if i ask "stupid" questions.

Im want to open a file named "Alexander".
The name of the file is stored in an Ansisting.
So i want to add an ".txt" extension to open the file.
Then i want to read a line form the file and store it in an string named StringFromFile.

The only problem was that i get an Acces violation. So i searched for some treads on this site and found the following tread:
http://www.daniweb.com/forums/newthr...=newthread&f=8

After reading it i figured out that this char array may be stored in read-only memory. So my question is: is the acces violation generated because om trying to add ".txt" to char* temp?

I already have a solution by using char temp[] but i would still like to understand why the acces violation was genereted!

 AnsiString filename = "Alexander";
        std:string StringFromFile;
        char* temp = filename.c_str();

        strcat(temp, ".txt");

        ifstream myfile3;
        myfile3.open (temp);
        getline(myfile3, StringFromFile);
        myfile3.close();
        delete[] temp;
MY problem is .....
Given an input 'n' came from the user and display a pattern.
but my code is very long .... my code is only for 1-10 numbers i need to display any numbers that input of the users can u give me some short code or advice to make it easy or briefly...Thxxxxx
Ex. if n=6, display
Ex. output

  6 5 4 3 2 1
  6 5 4 3 2
    6 5 4 3
    6 5 4
      6 5
        6

#include<iostream.h>
#include<conio.h>
main()
{
int n1,i;
char c1;
textcolor(YELLOW);
a:
clrscr();
cout<<"Enter a number :";
cin>>n1;
for (i=n1;i>0;i--)
{
cout<<" "<<i;
}
cout<<endl<<" ";
for (i=n1;i>1;i--)
{
cout<<" "<<i;
}
cout<<endl<<"  ";
for (i=n1;i>2;i--)
{
cout<<" "<<i;
}
cout<<endl<<"  ";
for (i=n1;i>3;i--)
{
cout<<" "<<i;
}
cout<<endl<<"    ";
for (i=n1;i>4;i--)
{
cout<<" "<<i;
}
cout<<endl<<"    ";
for (i=n1;i>5;i--)
{
cout<<" "<<i;
}
cout<<endl<<"      ";
for (i=n1;i>6;i--)
{
cout<<" "<<i;
}
cout<<endl<<"      ";
for (i=n1;i>7;i--)
{
cout<<" "<<i;
}
cout<<endl<<"        ";
for (i=n1;i>8;i--)
{
cout<<" "<<i;
}
cout<<endl<<"        ";
for (i=n1;i>9;i--)
{
cout<<" "<<i;
}
{
cout<<""<<endl<<""<<endl;
cout<<"Do you want to try another number or EXIT...?"<<endl;
b:
cout<<"Press 'y' if you want to try another number and 'n' to exit:";
cin>>c1;
        if ( c1=='y' || c1== 'Y')
        goto a;
        else if (c1=='n' || c1=='N')
        cout<<endl<<"Press Any Key to EXIT";
        else
        {
        cout<<"Invalid input, Choose again"<<endl;
        goto b;
        }
}
getch();
}

how to send keystrokes to an arbitrary application?

by TheGhost at 03:02 AM, 02/08/2010

hi, i need to send keystrokes an application (including, "enter", "left arrow", "right arrow", etc).

but how do i do that? i do not see any short and useful examples to doing it.

all i have got at the current moment is to get the foreground window using

HWND foregroundWindow = GetForegroundWindow();

i see the PostMessage function takes in HWND, UINT, WPARAM and LPARAM... but i have no idea which is for what. can somebody pls explain and teach me how to send keystrokes to an arbitrary application?

thanks.

doubts on c and c++

by vinodhkumar at 02:52 AM, 02/08/2010

(1)which are all access specifiers are applicable for class and why?

Why doesn't this work?

by invisi at 01:26 AM, 02/08/2010

It doesn't compile, why?

#include <iostream>
#include <string>

using namespace std;

int main()
{
       
        for(int cnt1 = 0, int cnt2 = 10;  cnt1<10; ++cnt1, --cnt2)
        {
                cout << cnt1 << "--------Hello!---------" << cnt2 << endl;
        }
       
        system("PAUSE");
}

Semi-Equality in C++

by OmarOthman at 01:15 AM, 02/08/2010

Dear All,

I want to do two mathematical operations, say
a / b

and

c / d

then test whether they are equal. I'm really very bad at computer errors, I think I need to read more about it (any reference is welcome). So, my question is: What is a suitable EPSILON to tolerate some computational errors in general? I know this depends on the complexity of the operation itself (because of propagating the errors at different steps of computation)... but what is a suitable start?
bool equals(double n1, double n2)
{
        return ((n1 - n2 <= EPSILON) || (n2 - n1 <= EPSILON));
}

checking where the space is entered

by dani_awais at 23:54 PM, 02/07/2010

HEllo everybody !!!
i have a little problem..
i m making a program in which i have to do bitwise addition.
mean if the 1st input is 111 and the 2nd input is 11 then the output is 1010 i have made my logic but where i have the problem is that i have to take the input in a single array and where the user enters the space it means that the input in 1st array has been ended and the input of second array is upto \0 i dont understand that how i check where the user enters the space thats the problem...
so kindly somebody plz explain it that how i will do this.....
thnx in advance

Poblem in Huffman

by moein_soltani at 23:28 PM, 02/07/2010

Hello all,
I have registerd lately, we have a project about the implemention of huffman algorithm...!
I have some problem...
first is that I want to read space and Enter from txt file how can i do that?
Next is how i should output to say that 0 and 1 are bit no byte!..
and finally how can i print huffman tree ... ?
Excuse me for elemntary question...
Tnx a lot...

What two numbers exit this programme?

by invisi at 22:40 PM, 02/07/2010

I wrote this programme but what two numbers you choose exit it?
can you guess just by looking? Because I can't :(

#include <iostream>
#include <string>

using namespace std;

int main()
{

        bool aHo = true;
        int a = 0;
        int b = 0;
       
        while(aHo)
        {
        cout << "Enter Number one: ";
        cin >> a;
        cout << endl;
        cout << "Enter NUmber two: ";
        cin >> b;
        cout << endl;
       
        for (int i = 0; i< 2; i++)
                for (int j = 0;  j < 2; j++)
                        for (int z = 0; z < 2; z++)
                                for (int v = 0; v < 2; v++)
                                        cout << a++ << " " << ++b << " " << ++a << " " << b++ << endl;
        a++;
                if (a == 30 && b == 34)
                        aHo = false;
        }


        system("PAUSE");
}

Concatenating two linked lists

by spirit3ch at 20:40 PM, 02/07/2010

Hi guys, I am supposed to implement a sequence using linked list. But I seem to have an error in the code. As I am getting trash for the results of the concatenate function. It might be a problem with my constructor too. I am not sure. Please help. I have pasted the code.

#include <iostream>
using namespace std;

typedef int ElementType;

struct Node
{
      ElementType data;
      Node* next;

};

class Sequence
{
      public:
            Sequence();
           
            Sequence(ElementType s);
           
            ~Sequence();
           
           
     
                       
                        Sequence concatenate(Sequence &s);
           
            void insert(ElementType s);
            ElementType remove();
           
            bool isEmpty();
            void printSeq();
           
      private:
              Node* head;
             
};

#include "sequence.h"



Sequence::Sequence()
{
                    head = NULL;
}

Sequence::~Sequence()
{
      while(head != 0)
      {
                  Node* iter = head;
                  head = head->next;
                  delete iter;
      }
}

                 
                           
                           
                           
Sequence::Sequence(ElementType s)
{
      Node *temp = new Node;
      temp->data = s;
      temp->next = head;
      head = temp;
   
                   
}


void Sequence::insert(ElementType s)
{
    Node *temp = new Node;
    temp->data = s;
    temp->next = head;
    head = temp;
   
   
}
       
ElementType Sequence::remove()
{
        ElementType delnode;
        Node* temp;
        if (head != NULL)
    {
                temp = head;
                head = head->next;
                delete temp;
        }

        return delnode;

}
Sequence Sequence::concatenate(Sequence &seqb)
{
        Sequence seqc;
               
        Node* iterator = head;
        while (iterator != NULL)
        {
              seqc.insert(iterator->data);
              iterator = iterator->next;
        }
       
        Sequence tempseq;
        while (seqb.isEmpty() == false)
        {
              ElementType bnode;
              bnode = seqb.remove();
              seqc.insert(seqb.remove());
              tempseq.insert(bnode);
             
        }
       
        while (tempseq.isEmpty() == false)
        {
              ElementType tnode;
              tnode = tempseq.remove();
              seqb.insert(tnode);
             
        }
  return seqc;
 
}

bool Sequence::isEmpty()
{
        return(head == NULL);

}

void Sequence::printSeq()
{
        Node* iterator = head;
        if (head != NULL) {
                do
                {
                        cout << iterator->data << " ";
                        iterator = iterator->next;
                }while(iterator != NULL);
        }
        cout << endl;
}

int main()

{
       
        cout << "Some simple normal tests" << endl;
       
        Sequence s1;
       
        //some inserts
        s1.insert(4);
        s1.insert(8);
        s1.insert(15);
        s1.insert(16);
        s1.insert(23);
        s1.insert(42);
       
        //Should print out list
        cout << "List printed is: ";
        s1.printSeq();
        cout << "It should be 42 23 16 15 8 4" <<endl;
       
       
        s1.remove();
        s1.remove();
        s1.remove();
       
       
        cout << "List printed is: ";
        s1.printSeq();
        cout << "It should be 15 8 4" <<endl;
       
       
        Sequence s2 = s1;
       
        cout << "Should be same list again." <<endl;
        s1.printSeq();
       
        cout << "Should be same list again." << endl;
        s1 = s2;
        s1.printSeq();
        cout << "This is s2." << endl;
        s2.printSeq();
       
        s1.insert(8);
        s1.insert(15);
        s1.insert(16);
       
        cout << "These two should be different" << endl;
       
        s1.printSeq();
        s2.printSeq();
       
       
        Sequence s3 = s1.concatenate(s2);

        cout << "This is the concatenated list" << endl;
       
        s3.printSeq();
   
    cout << "Sequence 1" << endl;
   
    s1.printSeq();
   
    cout << "Sequence 2" << endl;
   
    s2.printSeq();
 
}

getline string literal from file C++

by iamfabian at 19:39 PM, 02/07/2010

Totally new to C++, so please forgive me...

I'm trying to have a user input a filename and then check the file for all string literals.

The output should return the string literal (not the whole line, which is what I am getting).

Also, I have to ensure it ignores comments that include quotations.

I've tried doing a: line.find("\""); to get the string literals but pulling my hair out over here!

HELP! Your expert guidance please!!



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

int main( int argc, char* argv[] ) {

        //Prompt to open file, loop until proper file is input...
        ifstream infile;
        string filename;
       
        do {
                cout << "Enter file name:";
                cin >> filename;
                infile.open(filename.c_str());
                        if (!infile) {
                                cerr << "Cannot open file: " << filename << "\n" << endl;
                        }
                       
        } while (!infile);

       
        string line;
        int counter = 0;


       
        while( getline(infile,line) ){ 
               
                // Counter for line number(s)...
                ++counter;
               

       

                // Check for string literal(s)...
                std::string::size_type pos = line.find("\"");               
                if(pos != std::string::npos){                       
                        std::string sentence = line.substr(pos);                       
                       
                        // Print out filename, line number(s), and "string literal"
                        cout << filename << " line # " << counter << ", "  << sentence << "\n";       
                }
        }


        infile.close();
    system("pause");
        return 0;
The function I am trying to write is supposed to be recursive and does the following:
Return the number of ways that all n2 elements of a2 appear in the n1 element array a1 in the same order (though not necessarily consecutively). The empty sequence appears in a sequence of length n1 in 1 way, even if n1 is 0.

For example, if a1 is the 7 element array
"Bart" "Lisa" "Maggie" "Marge" "Lisa" "Maggie" "Homer"
then for this value of a2 the function must return
"Bart" "Marge" "Maggie" 1
"Bart" "Maggie" "Homer" 2
"Marge" "Bart" "Maggie" 0
"Lisa" "Maggie" "Homer" 3

So far, I have written this much:
int countIncludes(const string a1[], int n1, const string a2[], int n2)
{
        if (n2 == 0)
                return 1;
        if (n1 == 0)
                return 0;
        else
        {
                if (a1[0] == a2[0])
                        return countIncludes(a1+1, n1-1, a2+1, n2-1);
                else
                        return countIncludes(a1+1, n1-1, a2, n2);
        }
}

But it is incomplete and I know it does not work properly. I need help figuring out how to do this problem--just a method about how to go about this would be extremely helpful.

Thank you so much in advance!

Linker error

by david tran at 17:59 PM, 02/07/2010

Hello,

I am recompiling a project using Borland C++ builder 6. The recompile process failed due to linker error. The message was:

"[Linker Fatal Error] Fatal, unable to open file ABCC.lib"

I removed the ABCC references from the project and environment options, but the same error still occurred.

I even tried manually removed all ABCC references in the .bpr file, but the linker error still occurred.

Also, what is the ABCC.lib?

Any help is appreciated.

Thanks in advance,

Tuong,

C++ Win32 Input Help

by Hawkpath at 17:15 PM, 02/07/2010

Hi, I'm trying to create a simple program in Win32 and I can't find how to accept input in the form of text. Like "What's your name: ___" then the user enters their name and my program can evaluate the input. I have already googled this for a long time, so please don't give me lmgtfy answers. Thank you.

Object type in C++

by WargRider at 15:03 PM, 02/07/2010

Dear Community,

I know that Java and C# and various OTHER programming languages support a variable type Object, which is basically a variable that can hold ANY kind of variable type, from strings to booleans. I was wondering if this is possible in C++, I REALLY badly need something of that kind, anyone know where I can get something like that?

error C2447: '{' : missing

by khaled.s at 14:30 PM, 02/07/2010

Can you please tell me what's wrong? I get this error:

error C2447: '{' : missing function header (old-style formal list?)
//
//        Area= 1/2 | (x1y2 - x2y1) + (x2y3 - x3y2) + (x3y1 - x1y3) |
//        (distance)^2 = (x-difference)^2 + (y-difference)^2
//        v= sqrt[ s(s-a)(s-b)(s-c) ]
//        c^2= A^2 + B^2 - 2 A B cos Z
//        Z = angle between A and B
//        area of triangle = 1/2 AB sin Z

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

int main()

{
        float x1, x2, x3, y1, y2, y3, Area;


                cout << "Please enter the value of x1: ";
               
                cin >> x1;

                cout << "Please enter the value of y1: ";

                cin >> y1;

                cout << "Please enter the value of x2: ";

                cin >> x2;

                cout << "Please enter the value of y2: ";

                cin >> y2;

                cout << "Please enter the value of x3: ";

                cin >> x3;

                cout << "Please enter the value of y3: ";

                cin >> y3;

                Area = 0.5 * abs((x1*y2 - x2*y1) + (x2*y3 - x3*y2) + (x3*y1 - x1*y3));

                cout << "Area is: " << Area << endl;

                return 0;
               
}

{


        float s, a, b, c, V, distance, x1, x2, x3, y1, y2, y3, perimeter;

        cout << "Please enter x1: ";

        cin >> x1;

        cout << "Please enter x2: ";

        cin >> x2;

        cout << "Please enter x3: ";

        cin >> x3;

        cout << "Please enter y1: ";

        cin >> y1;

        cout << "Please enter y2: ";

        cin >> y2;

        cout << "Please enter y3: ";

        cin >> y3;


        a = sqrt( pow( (x2-x1, 2)) +  pow((y2-y1, 2) ));

        b = sqrt( pow( (x3-x2, 2)) +  pow((y3-y2, 2) ));

        b = sqrt( pow( (x3-x1, 2)) +  pow((y3-y1, 2) ));

        Perimeter = a + b + c;

        s = Perimeter / 2;

        V = sqrt ( s*(s-a)*(s-b)*(s-c) );

        cout << "Area is: " << V << endl;


        return 0;


}

Execution problem

by Violet_82 at 14:14 PM, 02/07/2010

Hi there,
I am experiencing a problem during the program execution.
Here is the program:
#include <iostream>

using std::cout;
using std::cin;

int additions (int a, int b, int c)

{
        int k;
        k = a+b-c;
        return k;
}

int main()

{
        int s;
        int x;
        int y;
        int z;
        cout << "The first number is: \n";
        cin >> x;
        cout << "The second number is: \n";
        cin >> y;
        cout << "The third number is: \n";
        cin >> z;

        s = additions (x,y,z);
       
        cout << "The result is: " << s << "\n";

        if (s == 4)
        cout << " \a\a\a";
        return 0;
}

Basically, when I click on the exe file in the debug folder, the program doesn't execute properly: it asks for the first number, second and third and then when I click enter the terminal disappears (I am using windows XP and the compiler is VC++ 6.0 trial copy).

If I instead compile the program and run it from VC++ (with ctrl F5) everything goes well...what am I doing wrong?
Thanks
Ok so a little bit of background, I am trying to write a boggle solver, I had everything working until I tried to implement a Binary Search Tree for storing the words found on the board, when I tried to do this I got the following errors:

Error 1 error C2146: syntax error : missing ';' before identifier 'foundWord' line 24
Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int line 24
Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int line 24

boggle.h
#pragma once
#include<iostream>
#include<string>
#include<ctime>
#include<fstream>
#include"HashTable.h"
#include"SLL.h"
#include"BST.h"

using namespace std;

class boggle
{
        struct Piece
        {
                char letter;
                bool isUsed;
        };
       
       
        Piece boggleBoard[3][3];
        HashTable WordListHT; //Calls HashTable
        string soFar;
        BST foundWord; // Creating a Binary Search tree for any found words       

public:
        boggle(void);
        ~boggle(void);

        void LoadWordList(string name);
        void CreateBoard();
        void PrintBoard();
        void WordSearch();
        void WordSearch(int i, int j); // overloaded function for recursive call during search
};

copy of BST.h
#pragma once
#include<iostream>
#include<string>
#include"boggle.h"

using namespace std;

class BST
{
        struct Node
        {
                string element;
                Node* left;
                Node* right;
        };

        Node* root;
public:
        BST(void);
        ~BST(void);

        void Insert(string data);
        void PreOrder();
        void PreOrder(Node* n);
};

and just to make sure I'm not missing anything stupid
BST.cpp
#include "BST.h"

BST::BST(void)
{
        root = 0;
}

BST::~BST(void)
{
}
void BST::Insert(string data)
{
        Node* n = new Node;
        n->element = data;
        n->left = 0;
        n->right = 0;
        // Special case if root == 0
        if(root == 0)
        {
                root = n;
                return;
        }
       
        // Creating a new node for insertion
       

        //Create tmp to traverse nodes
        Node* tmp = root;
       
        // Use a while loop to determine where the node is inserted
        while(tmp) // While tmp has some value besides NULL(0)
        {
                // if data less then tmp->element then go left
                if(data < tmp->element)
                {
                        // if tmp->right == 0 then insert here
                        if(tmp->left == 0)
                        {
                                tmp->left = n;
                                return;
                        }
                        // else procede to next node
                        else
                        {
                                tmp = tmp->left;
                        }
                }
                // else go left
                else
                {
                        // if tmp->right == 0 then insert here
                        if(tmp->right == 0)
                        {
                                tmp->right = n;
                                return;
                        }
                        // else procede to next node
                        else
                        {
                                tmp = tmp->right;
                        }
                }
        }
}

The Binary Search Tree was originally intended to take ints, but for this project need it to take strings.

C++ Help With Standard Deviation

by ppotter3 at 12:08 PM, 02/07/2010

Hello, I am working on a program that takes an integer array filled from a random number generator. These values are suppose to be from -5000 to 5000, 2500 of them. Then I want to find the standard deviation of the numbers in the array. I am required to use and integer array, calculate the average, returns the average which is a floating point value. Then I calculate the standard dev. I am having a problem with casting certain values. I am suppose to use integers and floats and I can't get it to work. I pretty sure I am suppose to use static cast but it wasn't working so I took it out. Any help would be greatly appreciated, and imput would be great too. I really want to get this working, thank you.


heres my code:


Driver
//  AUTHOR:                Page Lynn Potter
//  CLASS:                CIS 2275 C++ II
// PROGRAM:                Quiz #1  |  C++ ...Standard Deviation
//  E-MAIL:                ppotter03@inbox.com
//    FILE:                Driver.cpp

#include <iostream>
#include <iomanip>

#include "Functions.h"
using namespace std;

int main()
{
        // Declared Variables
        int Numbers[2500];
        int Total = 2500;
        float StandardDev, Mean;

        // Program description, program name, & author info.
        cout <<  "\n -----------------------------------------------------  \n";
        cout <<  "\n        C++ STATISTICAL ANALYSIS via STANDARD DEVIATION    \n";
        cout <<  "\n -----------------------------------------------------  \n";
        cout << setw(15) <<  "\n        AUTHOR:        "          << setw(15) << "        Page Lynn Potter ";
        cout << setw(17) <<  "\n        CLASS:        "    << setw(5)  << "        CIS 2275  ";
        cout << setw(10) <<  "\n        ASSIGNMENT: "  << setw(20) << "        QUIZ #1 \n";
        cout <<  "\n -----------------------------------------------------  \n";

        cout << "\n This program computes two statistical values for an array "
                << "\n of 2500 values rainging in value from -5000 to +5000. ";
        cout << "\n The sum and average of the values will be calculated, "
                << "\n and diplayed for viewing as well as the standard deviation. \n";

        FillArray(Numbers, Total);

        float Average = AveArray(Numbers, Total);
       
        cout << setw(25) << "\n RESULTS \n";
        cout <<  "\n -----------------------------------------------------  \n";
       
        cout.precision(4);
        cout.setf(ios::fixed);

        cout << "\n AVERAGE =  " << setw(10) << Mean << "\n";

        float StandardDeviation = StdDeviation(Numbers, Total, Mean);

        cout << "\n STANDARD DEVIATION:  " << setw(10) << StandardDev << "\n";

        return (0);
}


Functions
//  AUTHOR:                Page Lynn Potter
//  CLASS:                CIS 2275 C++ II
// PROGRAM:                Quiz #1  |  C++ ...Standard Deviation
//  E-MAIL:                ppotter03@inbox.com
//    FILE:                Functions.cpp

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

using namespace std;

void FillArray(int Numbers[], int Total)
{
        srand(123);
       
        for (int i = 0; i < Total; i++)
                {
                        // Gives me 0 - 10000
                        Numbers[i] = ((rand()%10000 + 1) - 5000);
                }

}

float AveArray(int Numbers[], int Total)
{
        // Declared Variables
        int sum = 0;
       
        // Just to make sure there isn't any junk values.
        float Mean = 0,0;
       
        for (int i = 0; i < Total; ++i)
                {
                        sum += Numbers[i];
                }
               
       
        Mean = sum/Total;

        return Mean;
}

float StandardDev(int Numbers[], int Total, float Mean)
{
        // Declared Variables
        float StandardDev = 0.0;
        int Sum2 = 0;

        for (int i = 0; i < Total; ++i)
                {
                        Sum2 += pow((Numbers[i] - Mean), 2);
                }
 
        StandardDev = sqrt(Sum2 / (Total - 1));

        return StandardDev;
}


Header
//  AUTHOR:                Page Lynn Potter
//  CLASS:                CIS 2275 C++ II
// PROGRAM:                Quiz #1  |  C++ ...Standard Deviation
//  E-MAIL:                ppotter03@inbox.com
//    FILE:                Functions.h

#include <iostream>

using namespace std;

/* The FillArray() is passed the integer array and total number
  (size) of the array. It then uses rand() to fill the array
  with values from -5000 to +5000. */
void FillArray(int Numbers[], int Total);

/* The AveArray() calculates the average (mean) of the array.
  It is passed the array, total number (size) and returns, a
  floating point value. */
float AveArray(int Numbers[], int Total);

/* The StandardDec() is passed the array, array size, and the
  average (mean) value. It then calculates and returns the
  standard deviation. */
float StandardDev(int Numbers[], int Total, float Mean);

Standard Deviation

by angel6969 at 11:55 AM, 02/07/2010

//Define a function that takes a partially filled array of numbers
//as its argument and returns the standard deviation of the numbers in
//the partially filled array. Since the partially filled array requires
//two arguments, the function will have two formal parameters: an array
//parameter and a formal parameter of type int that gives the number of the
//array positions used. The numbers in the array will be double. The task is
//the standard deviation of a list of numbers is a measure of how much the number
//deviate from the average. If the standard deviation is small the numbers are
//clustered close to the average and if the standard deviation is large, the numbers
// are scattered far from the average. The standard deviation, S,of a list of N
//numbers x, is defined as follows: where x is the average of N.

S = think square root symbol, N, sum(x, -x)to second power, i = 1, over N

I have not started the code yet as I have no real idea of what this wants .... if it could be explained or shown to me of what is required then I can start building code for this .... does anyone understand this enough to help me...

CodeLite

by iamcreasy at 11:33 AM, 02/07/2010

I have just started using CodeLite.
http://www.codelite.org/

It looks impressive....
I was using Codeblocks.But it's lack of features and less frequent stable release has disappointed me.Though, it's subversion is very frequent.

I am no expert, but CodeLite looks better then codeblocks.
But, if it is better then codeblocks then why it is not popular as codeblocks or DevC++(whose stable release was many many years ago).

Any comments about this?

....and do anyone know something about Eclipse.It looks quite impressive.

Plume Boundary

by smith73 at 10:35 AM, 02/07/2010

I have to modify the program so that it can read 10 sample points and determine which are contained in the plume boundary. This is my first object oriented class and I have made it run ten times but I dont think that is correct. Please advise.... Thanks.

data given:

0 0 19 44
3 5 20 55
4 16 25 31
7 35 24 4
10 22 10 3

#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;
const int LARGE_NUM = 1.0e10;

struct Point
{
public:
        double x, y;
};

struct Line_seg
{
public:
        Point endpt1, endpt2;
        double slope, intercept;
};

class Boundary_map
{
private:
        enum {NUM_MAP_PTS = 10};
        Point boundary_pts[NUM_MAP_PTS + 1];

public:
        Boundary_map ();
        void read_boundary_pts ();
        void map_wrap_around ();
        Point* get_boundary_pts ();
        int get_num_boundary_pts ();
};

class Probe
{
private:
        Point sample_pt, endpt1, endpt2;
        int num_crosses;
        Point probe_line_intersect (Line_seg);
        int probe_line_seg_intersect (Point, Line_seg);

public:
        Probe ();
        void read_sample_pt ();
        void check_map_boundary (Point*, int);
};

Boundary_map :: Boundary_map ()
{
        int i;
        for (i = 0; i < NUM_MAP_PTS + 1; i++)
        {
                boundary_pts[i].x = 0;
                boundary_pts[i].y = 0;
        }
}

void Boundary_map :: read_boundary_pts ()
{
        int i;
        ifstream infile ("C:\\BNDARY.DAT");

        for (i = 0; i < NUM_MAP_PTS; i++)
        {
                infile >> boundary_pts[i].x;
                infile >> boundary_pts[i].y;
        }
}

void Boundary_map :: map_wrap_around ()
{
        boundary_pts[NUM_MAP_PTS] = boundary_pts[0];
}

Point* Boundary_map :: get_boundary_pts ()
{
        return (boundary_pts);
}

int Boundary_map :: get_num_boundary_pts ()
{
        return (NUM_MAP_PTS + 1);
}

Probe :: Probe ()
{
        sample_pt.x = 0;
        sample_pt.y = 0;
        endpt1.x = 0;
        endpt1.y = 0;
        endpt2.x = LARGE_NUM;
        endpt2.y = 0;
        num_crosses = 0;
}

void Probe :: read_sample_pt ()
{
        cout << "Enter the x and y coordinates of the sample point" << endl;
        cin >> sample_pt.x >> sample_pt.y;
        endpt1 = sample_pt;
        endpt2.y = sample_pt.y;
}

Point Probe :: probe_line_intersect (Line_seg map_line_seg)
{
        Point intersect_pt;
        double probe_slope, probe_intercept;

        if (fabs (map_line_seg.endpt2.x - map_line_seg.endpt1.x) < 1.0E-20)
        {
                intersect_pt.x = map_line_seg.endpt1.x;
                intersect_pt.y = endpt1.y;
        }
        else
        {
                map_line_seg.slope = (map_line_seg.endpt2.y
                        - map_line_seg.endpt1.y) / (map_line_seg.endpt2.x
                        - map_line_seg.endpt1.x);

                map_line_seg.intercept = map_line_seg.endpt2.y
                        - map_line_seg.slope * map_line_seg.endpt2.x;

                probe_slope = 0.0;
                probe_intercept = sample_pt.y;

                if (fabs (map_line_seg.slope) < 1.0E-20)
                {
                        intersect_pt.x = LARGE_NUM;
                        intersect_pt.y = LARGE_NUM;
                }

                intersect_pt.x = (probe_intercept - map_line_seg.intercept) /
                        (map_line_seg.slope - probe_slope);

                intersect_pt.y = map_line_seg.slope * intersect_pt.x
                        + map_line_seg.intercept;
        }

        return (intersect_pt);
}

int Probe :: probe_line_seg_intersect (Point intersect_pt, Line_seg seg2)
{
        Line_seg seg1;
        double x_low_1, x_high_1, x_low_2, x_high_2;
        double y_low_1, y_high_1, y_low_2, y_high_2;

        seg1.endpt1 = endpt1;
        seg1.endpt2 = endpt2;

        x_low_1 = (seg1.endpt1.x < seg1.endpt2.x) ?
                seg1.endpt1.x : seg1.endpt2.x;

        x_high_1 = (seg1.endpt1.x > seg1.endpt2.x) ?
                seg1.endpt1.x : seg1.endpt2.x;

        x_low_2 = (seg2.endpt1.x < seg2.endpt2.x) ?
                seg2.endpt1.x : seg2.endpt2.x;

        x_high_2 = (seg2.endpt1.x > seg2.endpt2.x) ?
                seg2.endpt1.x : seg2.endpt2.x;

        y_low_1 = (seg1.endpt1. y < seg1.endpt2.y) ?
                seg1.endpt1.y : seg1.endpt2.y;

        y_high_1 = (seg1.endpt1. y > seg1.endpt2.y) ?
                seg1.endpt1.y : seg1.endpt2.y;

        y_low_2 = (seg2.endpt1. y < seg2.endpt2.y) ?
                seg2.endpt1.y : seg2.endpt2.y;

        y_high_2 = (seg2.endpt1. y > seg2.endpt2.y) ?
                seg2.endpt1.y : seg2.endpt2.y;

        if ((x_low_1 <= intersect_pt.x && intersect_pt.x
                <= x_high_1) && (x_low_2 <= intersect_pt.x &&
                intersect_pt.x <= x_high_2) && (y_low_1
                <= intersect_pt.y && intersect_pt.y <= y_high_1) &&
                (y_low_2 <= intersect_pt.y && intersect_pt.y
                <= y_high_2))
        {
                return (1);
        }
        else
        {
                return (0);
        }
}

void Probe :: check_map_boundary (Point* bnd_pt, int num_pts)
{
        int i, does_cross, even_odd;
        Point intersect_pt;
        Line_seg map_line_seg;

        for (i = 0; i < num_pts - 1; i++)
        {
                map_line_seg.endpt1 = bnd_pt[i];
                map_line_seg.endpt2 = bnd_pt[i + 1];

                intersect_pt = probe_line_intersect
                        (map_line_seg);

                does_cross = probe_line_seg_intersect
                        (intersect_pt, map_line_seg);

                num_crosses += does_cross;
        }

        even_odd = num_crosses % 2;

        if (even_odd == 0) cout << "The sample point is outside the "
                "plume." << endl;

        if (even_odd == 1) cout << "The sample point is inside the "
                "plume." << endl;
}

int main ( )
{
        Boundary_map plume_map;
        Probe probe_from_water_sample;
        int counter;
        for (counter = 1; counter <= 10; counter++)
        {
        plume_map.read_boundary_pts ();

        plume_map.map_wrap_around ();

        probe_from_water_sample.read_sample_pt ();

        probe_from_water_sample.check_map_boundary
                (plume_map.get_boundary_pts (),
                plume_map.get_num_boundary_pts ());
        }
        return 0;
}
for i<-1 to n do
for j<-1 to n^2 do
write(i*j)
end-for
end-for

opinion

by sidra 100 at 09:29 AM, 02/07/2010

“Although for consistent and reusable design we follow Object Oriented paradigms; “structured approach” has still its worth in some imperative and critical applications. Support or contradict this statement with solid arguments.

Searching through text files for individual words

by StaticX at 08:28 AM, 02/07/2010

Hi,

Can anyone help me with this problem.For example i have a text file called food.txt with contents


1 apples
2 oranges
3 mango
4 bananna


What i would like to do is enter the choice of fruit into a string and loop through the file until the word is found.My problem being i dont fully understand any of the examples online and would be grateful if someone could point me in the right direction.

Here is my code so far

main(){
   
    char filename[size];
    char line[size];
    string fruit;
   
   
    cout << "Please enter filename: ";
    cin >> filename;
   
    cout << "enter fruit:" << endl;
    cin >> fruit;
    cout << fruit;
   
   
    cout << "\n Filename is: " << filename << endl;
   
    cout << "Opening file.." << endl;
   
    fstream* file = new fstream(filename,fstream::in);
   
    while(file->getline(line,size) != NULL)
    {
        cout << line;
       
        // if the line is the same as fruit entered print out the line(this does not work!)
        if(line == fruit)
        {
            cout << line;
        }
    }
   
    system("PAUSE");
   
   
}

Problem with array within c++ class

by hawkoftheeye at 07:52 AM, 02/07/2010

Hiya.

Many apologies if the question I am about to ask has already been answered. I searched the forum, and found a couple of threads that seemed to be relevant to my problem, but none seemed to describe the problem fully.

I'm fairly new to C++, having only been using it seriously as part of my studies for the past 6 months or so.

My problem is this. I have a class which must contain two arrays of integers, eg:
class myClass
{
public:
    int firstArray[size];
    int secondArray[size];
    readValues();
};
The readValues function takes input from a text file containing a series of integers and should write it into the relevant array using ifstream. The problem is there is no way of knowing how many values will be in this text file beforehand. Having said that, the text file will not change in size during the program operation.

I'm not sure of the best way of approaching this. Is there a way of possibly defining that the array exists within the class, and define it's size later? Or can I define it later, either within the constructor or another function?

You help in solving this problem would be most appreciated.

Many thanks


Richard

Read number from string (mix of char and number)

by Tommy2010 at 06:58 AM, 02/07/2010

Hi!

I've been searching for reading number in a string containing mix of number and char for hours, but I've found the right code. The string has the format

q23 - q3 (or q23-q3)

I'd like to read the number '23' and store it in x, '3' --> y, and '-' --> z. Could you tell me how to do this?
Thanks!

Older code won't compile on newer compiler

by Ed Ashworth at 05:12 AM, 02/07/2010

I wrote some C++ programs and classes a few years ago using Visual C++ 6.0 as my editor/compiler. Recently I replaced the 6.0 with Visual C++ 2008 Express. Now, none of my older code will compile.
I read that there were some changes to the C++ standard library some time ago and I suspect the VC++ 2008's compiler incorporates these changes.
If I am correct, all I need is some documentation as to what was changed in the library so I can edit the source code and make it work again.
Can someone point me in the right direction so I can update my code to today's standards?
Thanks.
Uncle Ed

error in class

by sidra 100 at 04:54 AM, 02/07/2010

plz chk my code i m having error at line 35 and 36
#include <iostream>
#include <cstring>
using namespace std;

class strng
{
  char s[30];
    public:
          strng()
          {
                  strcpy(s,"");
                  }
    string getstring()
          {
            cout<<"enter the sting:";
            cin>>s;
          return s; 
                        }
    void displaystring()
    {
          cout <<"the string is:"<<s<<endl;
          }

                 
                         
                        const strng &operator+= (const strng &t);
                          };
                          const strng &strng ::operator+=(const strng &t)
                            {
                                    strng temp;
                                    strcpy (temp.s,"");
                                   
                                    strcat(temp.s,s);
                                    strcat(temp.s,t.s);
                                    s=temp;
                                    return s;
                                    }
                                   
                                   
                                   
          main()
          {
                    strng s1;
                    strng s2;
                    s1.getstring();
                    s2.getstring();
                      s1+=s2;
                    s1.displaystring();
                           

}
errors are:
35 C:\Dev-Cpp\ddd.cpp incompatible types in assignment of `strng' to `char[30]'

36 C:\Dev-Cpp\ddd.cpp invalid initialization of reference of type 'const strng&' from expression of type 'char*'

Help! Sequence using Linked Lists

by spirit3ch at 04:45 AM, 02/07/2010

Hi I am trying to implement a sequence using a linked list. I need to have the following functionalities: insert, remove and concatenate. The concatenate should not be destructive and the function call should be like. That is Seq1 and Seq2 should be preserved post function call.

Seq3 = Seq1.concatenate(seq2)

I have implemented the insert and remove functions, the constructors and the copy constructors successfully. But am having trouble with the concatenate function. For starters I have the following error after compiling:

169 C:\Users\...\sequence.cpp 'class Sequence' has no member named 'conacatenate'

So I can't even check my code. Please help. I am pasting my entire code, the header and the cpp in two parts

sequence.h
#include <iostream>
using namespace std;

typedef int ElementType;

struct Node
{
      ElementType data;
      Node* next;

};

class Sequence
{
      public:
            Sequence();
           
            Sequence(ElementType s);
           
            ~Sequence();
           
            Sequence(Sequence &rhs);
            Sequence concatenate(Sequence &seq);
                       
                       
           
            void insert(ElementType s);
            ElementType remove();
           
            bool isEmpty();
            void printSeq();
           
      private:
              Node* head;
             
};




sequence.cpp

#include "sequence.h"



Sequence::Sequence()
{
                    head = NULL;
}

Sequence::~Sequence()
{
      Node* iterator = head;
      Node* delnode;
      if (head!=NULL){
          do {
            delnode = iterator;
            iterator = iterator->next;
            delete delnode;
            } while (iterator != head);
          }
      head = NULL;
}

Sequence::Sequence(Sequence &rhs)
{
                            head = NULL;
                            Node*tail = head;
                            Node* iterRHS = rhs.head;
                           
                            if(iterRHS != NULL)
                            {
                                      head = new Node;
                                      head->data = iterRHS->data;
                                      head->next = NULL;
                                     
                                      iterRHS = iterRHS->next;
                                      tail = head->next;
                                     
                                      while (iterRHS != NULL)
                                      {
                                            tail->next = new Node;
                                            tail = tail -> next;
                                            tail->data = iterRHS->data;
                                            tail->next = NULL;
                                            iterRHS = iterRHS->next;
                                      }
                                     
                                      tail->next = head;
                    }
 
}                 
                           
                           
                           
                           
                           
                           
Sequence::Sequence(ElementType s)
{
      Node *temp = new Node;
      temp->data = s;
      head = temp;
      head->next = head;
          temp->next = head;
          head = temp->next;
}


void Sequence::insert(ElementType s)
{
    Node *temp = new Node;
    temp->data = s;
    temp->next = head;
    head = temp;
   
   
}
       
ElementType Sequence::remove()
{
        ElementType delnode;
        Node* temp;
        if (head != NULL)
    {
                temp = head;
                head = head->next;
                delete temp;
        }

        return delnode;

}

Sequence Sequence::concatenate(Sequence &seq2)
{
        Sequence seq3;
        Node* seq3head = new Node;
        seq3head = NULL;
        Node* seq3tail = seq3head;

        Node* iterSeq1 = head;

        if(iterSeq1 != NULL)
        {
                seq3head = new Node;
                seq3head -> data = iterSeq1->data;
                seq3head->next = NULL;
        }

        seq3tail = seq3tail->next;

        iterSeq1 = iterSeq1->next;
        while (iterSeq1 != NULL)
        {
                seq3tail -> next = new Node;
                seq3tail = seq3tail->next;
                seq3tail->data = iterSeq1->data;
                seq3tail->next = NULL;
                iterSeq1 = iterSeq1->next;
        }
        seq3tail->next = NULL;

        Node* iterSeq2 = seq2.head;

        if(iterSeq2 != NULL)
        {
                seq3tail->next = new Node;
                seq3tail = seq3tail->next;
                seq3tail->data = iterSeq2->data;
                seq3tail->next = NULL;
                iterSeq2 = iterSeq2->next;
        }
        seq3tail->next = NULL;
        return seq3;
}

void Sequence::printSeq()
{
        Node* iterator = head;
        if (head != NULL) {
                do
                {
                        cout << iterator->data << " ";
                        iterator = iterator->next;
                }while(iterator != NULL);
        }
        cout << endl;
}

int main()

{
       
        cout << "Some simple normal tests" << endl;
       
        Sequence s1;
       
        //some inserts
        s1.insert(4);
        s1.insert(8);
        s1.insert(15);
        s1.insert(16);
        s1.insert(23);
        s1.insert(42);
       
        //Should print out list
        cout << "List printed is: ";
        s1.printSeq();
        cout << "It should be 42 23 16 15 8 4" <<endl;
       
        //a couple of removes
        s1.remove();
        s1.remove();
        s1.remove();
       
        //Should print out list with three removed
       
        cout << "List printed is: ";
        s1.printSeq();
        cout << "It should be 15 8 4" <<endl;
       
        //This is the copy constructor
        Sequence s2 = s1;
       
        cout << "Should be same list again." <<endl;
        //this should print same list
        s1.printSeq();
       
        cout << "Should be same list again." << endl;
        s1 = s2;
        s1.printSeq();
       
        s1.insert(8);
        s1.insert(15);
        s1.insert(16);
       
        cout << "These two should be different" << endl;
       
        s1.printSeq();
        s2.printSeq();
       
       
        Sequence s3 = s1.conacatenate(s2);

        cout << "This is the concatenated list" << endl;
       
        s3.printSeq();

 
}

Use of "->" - simple question

by JustSuds at 04:42 AM, 02/07/2010

Hi everyone, I just can't seem to find an explanation for using this "->" in code, in C++. I've migrated from Java and C#, and haven't seen this notation before. Basic example:

CMesh *pMesh = WorldObjects[i]->m_pMesh;

As best as I can tell, this is the C++ equivalent of C#'s
WorldObjects[i].m_pMesh;
. (as if to say that m_pMesh is a member variable, or method of the WorldObjects object, but as it is only a code snippet, I cant check the classes to see)

Just a quick syntactic explanation is all I need. Thanks.
Hello everyone, i'm porting an application from C# to C++, and i find the syntax and all that of C++ rather cumbersome (though C/C++ was my first language).
I have a very specific question, and another few more-or-less general ones.
The specific question:
In C#:
Bitmap image;
BitmapData ImageData;
ImageData=image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat);
byte* walker = (byte*)ImageData.Scan0;
//Sift through the bytes using a for
for(int i=0; i< image.Height*ImageData.Stride;i++)
{
      string bit = Convert.ToString(*walker, 2);
      //Get the byte represented by walker, by dereferencing it
    //and convert the number (e.g. 235) to base 2, getting
    //a string of 1's and 0's.
      walker++;
    //Increment the pointer
}
Easy enough, huh?
Here's the C++ version, where i'm having difficulties:
Bitmap^ image;
BitmapData^ ImageData;
ImageData=image->LockBits(Rectangle(0,0,image->Width,image->Height),ImageLockMode::ReadWrite,image->PixelFormat);
IntPtr walker=ImageData->Scan0;
for(int i=0; i<Image->Height * ImageData-> Stride; i++)
{
        //1.How do i get the value at IntPtr?? Dereference does
      //not work.
      //2.How do i increment the pointer?
}
So my problems are, how do i increment IntPtr, and how do i get the value at its address (dereference) ?.
Thank you.
And now, general questions:
1. Why do i need to put the '^' sign when declaring stuff.
String^ myString;
2.How do i know when to use scope resolution operator :: or arrow sign -> ?
3.Why does this instruction:
if(!Regex::IsMatch(myString, "\[[0-9]{8}\]"))
{ //something }
give a warning that ']' and '[' are unrecognized escape characters? (in C# it worked...)
Thank you very much!

I really need help on a pseudo code!

by misfits86 at 23:02 PM, 02/06/2010

Input a list of positive numbers, terminated by 0, into an array Numbers. Then, display the array and the largest and smallest number in it.

Process, Input, Output information with variable names and type and complete pseudo code of the program (with declaration of variables, calling of modules, any modules, inputs, outputs, etc.)

This is what is being asked and I dont have a clue what to do. Can someone please help me. I would really appreciate it..

I guess this is it correct?

int[] Numbers;
Numbers = new int[50];
int K;
int Flag;
int Count;
int OneNumber;
int Temp;
String UserInput;
System. Console. WriteLine ("This program will sort 50 positive numbers for you");
System, Console. WriteLine ("The Program will show all numbers from smallest to highest and then display the lowest and highest number in the Array.
System. Console. WriteLine ("Enter your first positive number or enter a 0 to exit. ")
UserInput = System. Console. ReadLine;
OneNumber = int.Parse (UserInput);
Count = 0;
While (OneNumber = 0)
Numbers [Count] = OneNumber;
Count = Count + 1;
System. Console. WriteLine ("Enter another positive number or enter a 0 to exit.");
UserInput = System. Console. ReadLine;
OneNumber = int.Parse (UserInput);
Flag = 0;
While (Flag= 0)
Flag = 1;
For (K = 0; K = (Count - 2); K++)
If (Numbers [K] < Numbers [K + 1]
Temp = Numbers [K];
Numbers [K] = Numbers [K + 1];
Numbers [K + 1] = Temp;
Flag = 0;
System. Console. WriteLine ("Sorted List of Numbers);
For (K = 0; K <= (Count - 1); K+)
System. Console. WriteLine (Numbers [K])


Thank you

Car Class Homework HELP!!

by C++ Beginner at 21:27 PM, 02/06/2010

Problem: Write a class that defines a car. The car class stores the following data about a car:
Member Name Data Type
make string
model string
vin string
owner string
doors int
mileage float
gas tank float
trip float
gas remaining float

Create methods to set data into the data members and to read the data from the data members. Write a method to determine the gas mileage.

What I got so far is:

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

class car
{
private:
        string make,
                  model,
                  vin,
                  owner;
        int doors;
        float mileage,
                  gasTank,
                  trip,
                  gasRemaining;
public:
        string getMake();
        string getModel();
        string getOwner();
        int getDoors();
        float getMileage();
        float getGasTank();
        float getTrip();
        float getGasRemaining();
        double getGasMilease();
};

int main()
{
        car cars;

        cout << " Please enter Make of car: ";
        cin >> cars.make;

        return 0;
}

string car::getMake()
{
        return make;
}

I am getting the following errors:
1>.\CH 7 Addendum 2 Car Class.cpp(41) : error C2248: 'car::make' : cannot access private member declared in class 'car'
1> .\CH 7 Addendum 2 Car Class.cpp(15) : see declaration of 'car::make'
1> .\CH 7 Addendum 2 Car Class.cpp(13) : see declaration of 'car'

This week we just started to learn about classes so I am totally lost even after reading the textbook several times and looking over their examples. Can anyone help me understand what I am doing wrong with the class?

c++ error

by skorm909 at 20:47 PM, 02/06/2010

here is my script:

#include <iostream>
#include <cmath>

int main()
{
using namespace std;

int who;



cout << "how are you today? good, bad, or eh?" << endl;
cin >> who;
if (who == "good")
{
cout << "ahh thats pretty cool i guess..." << endl;
}
if (who == "bad")
{
cout << "LOL that sucks for you!!!!" << endl;
}
if (who == "eh")
{
cout << "EHHHHHHHHHHHHH!!!" << endl;
}
else
{
cout << "i dont know what that means? close and retry please..." << endl;
}
cout << "god im so bored" << endl;
cout << endl;
system("pause")
return 0;

}


i get an error :
ISO C++ forbids comparision between pointer and integer

how do i fix this? and what is actually causing this and why is it like that?


also im just starting out in codeing and wanted to know if there was a way i can make it so i can run it in anything besides CMD.
like if i could make it so when someone clicks on it , it opens up in like a window that i choose or something then it has buttons where it has the different types of code i put in there...

any help will be appreciated.
thanks.
Hello guys, that's my first post around here and I have a problem with binary files.

I'm writing a simple editor for my arkanoid clone game. This editor opens a binary file defined by this:
0-26 byte: Descriptor for the file. Once in each file.
27->(1141*n): Levels inside the file, each level has 1141 bytes.

Here starts my problems! The game and the editor use the "Files" class, which manipulates the stream, just loading and saving levels, if in editor. Everything works fine in editor but only if i have at least a blank level file!
The game of course can't continue if there are no file levels, but the editor needs to create one, and it can't!

I need to:
- Binary file;
- Open the file to write anywhere in it without losing previous content (eg: The user may have a file with 30 levels, but want to change level 2, so not just appending);
- Creating the file if it doesn't exist (eg: User deleted the file completely or it got corrupted, which is checked elsewhere); and
- Having only one file open all time (Maybe my error is here, don't know if this is good practice or not).

Here is the code i'm using for opening the file:

file.open(filename.c_str(), std::ios::in | std::ios::out | std::ios::ate | std::ios::binary);

This is outside the constructor, the game and editor call a load default level function containing this code, and the destructor closes the file.

What I already tried:
- Playing with the open modes:
//Recreates file everytime
file.open(filename.c_str(), std::ios::in | std::ios::out | std::ios::binary);
//Can't access beginning of file; Any seek(0) returns the pointer to the end of file (after last byte)
file.open(filename.c_str(), std::ios::in | std::ios::out | std::ios::app | std::ios::binary);
- Think to create a temp file only for output -> open the levels file in input only -> copy level to temp file -> close levels file -> reopen it in output mode (erased all content) -> Copy temp file back to level file -> close temp file. Seems to much trouble, but if it's the only way...
- Trying to seek backwards with negative values (eg:
seekp(-(levelSize), std::ios::cur)
) but it doesn't seem to work since it always goes forth!

Please guys, help me! I can post other parts of my code if you think it's relevant!

Thank you.

play wav files stored in 1D array using libsndfile

by pjawili18 at 19:24 PM, 02/06/2010

Hello,

I'm writing a c++ code that reads a wav file and stores read values to a 1D array of integers. After doing some manipulation, I am able to write the values of the array to a new output wav. I use libsndfile library to do the reading and writing (sf_read & sf_write).

I then play this output wav by using Audiere library. I know the manipulation works since the sound played is the one I expect.

My question is how can I play the contents of the array without having to write it to secondary storage just to have it read again?

Thanks for your help! ^_^

Wierd Errors

by tomtetlaw at 19:09 PM, 02/06/2010

When I compile my code, I get these errors:

------ Build started: Project: engine, Configuration: Debug Win32 ------
Compiling...
baseanimating.cpp
c:\program files\microsoft visual studio 9.0\vc\include\time.h(39) : error C2143: syntax error : missing ';' before 'string'
c:\program files\microsoft visual studio 9.0\vc\include\time.h(39) : error C2059: syntax error : 'string'
c:\program files\microsoft visual studio 9.0\vc\include\time.h(39) : error C2143: syntax error : missing ';' before '{'
c:\program files\microsoft visual studio 9.0\vc\include\time.h(39) : error C2447: '{' : missing function header (old-style formal list?)
c:\program files\microsoft visual studio 9.0\vc\include\ctime(19) : error C2039: 'clock_t' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(19) : error C2873: 'clock_t' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(21) : error C2039: 'asctime' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(21) : error C2873: 'asctime' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(21) : error C2039: 'clock' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(21) : error C2873: 'clock' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(21) : error C2039: 'ctime' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(21) : error C2873: 'ctime' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(22) : error C2039: 'difftime' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(22) : error C2873: 'difftime' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(22) : error C2039: 'gmtime' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(22) : error C2873: 'gmtime' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(22) : error C2039: 'localtime' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(22) : error C2873: 'localtime' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(23) : error C2039: 'mktime' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(23) : error C2873: 'mktime' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(23) : error C2039: 'strftime' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(23) : error C2873: 'strftime' : symbol cannot be used in a using-declaration
c:\program files\microsoft visual studio 9.0\vc\include\ctime(23) : error C2039: 'time' : is not a member of '`global namespace''
c:\program files\microsoft visual studio 9.0\vc\include\ctime(23) : error C2873: 'time' : symbol cannot be used in a using-declaration
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(7) : error C2146: syntax error : missing ';' before identifier 'counter'
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(7) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(7) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(11) : error C2061: syntax error : identifier 'clock_t'
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(9) : error C2614: 'CTimer' : illegal member initialization: 'counter' is not a base or member
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(13) : error C2065: 'clock_t' : undeclared identifier
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(13) : error C2146: syntax error : missing ';' before identifier 'tick'
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(13) : error C2065: 'tick' : undeclared identifier
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(13) : error C2039: 'clock' : is not a member of 'std'
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(13) : error C3861: 'clock': identifier not found
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(15) : error C2065: 'tick' : undeclared identifier
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(15) : error C2065: 'counter' : undeclared identifier
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(15) : error C2065: 'ms' : undeclared identifier
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(17) : error C2065: 'counter' : undeclared identifier
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\timer.h(17) : error C2065: 'tick' : undeclared identifier
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\baseanimating.cpp(28) : warning C4018: '<' : signed/unsigned mismatch
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\baseanimating.cpp(39) : warning C4018: '<' : signed/unsigned mismatch
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\baseanimating.cpp(50) : warning C4018: '<' : signed/unsigned mismatch
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\baseanimating.cpp(61) : warning C4018: '<' : signed/unsigned mismatch
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\baseanimating.cpp(72) : warning C4018: '<' : signed/unsigned mismatch
Build log was saved at "file://c:\Documents and Settings\tom\My Documents\Visual Studio 2008\Projects\engine\engine\Debug\BuildLog.htm"
engine - 39 error(s), 5 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

The only file that is mine out of those errors is time.h:
#ifndef TIMER_H
#define TIMER_H

#include <ctime>

class CTimer {
    clock_t counter;
public:
    CTimer(): counter(0) {}

    bool elasped(clock_t ms)
    {
        clock_t tick = std::clock();

        if(tick - counter >= ms)
        {
            counter = tick;
            return true;
        }

        return false;
    }
};

#endif //TIMER_H

Can someone help me to fix these errors?

C++ Web Server wont return image

by Dizzzy at 17:47 PM, 02/06/2010

Ok so ive been writing code for a web server to return requested files, It works well for html and txt files but when an image is requested all i recieve is the url of the file... In firefox in conqueror i dont get anything. All i do is read the file and send it that is all so that part is fine. I think the problem is somewhere in the headers of the response of the server.

const char *r1="HTTP/1.1 200 OK\r\n";
        const char *r2="Date: ";
        const char *r3="\r\nConnection: close";
        const char *r4="\r\nContent-Length: ";
        const char *r5="\r\nContent-Type: ";
        const char *r6="\r\n\r\n";
        const char *r7="<Head><Title>Page Found</Title>";
            const char *r8="<Body> File: ";
            const char *r9=" was found</body></head>\r\n";
        strcpy(returned,r1);
            strcat(returned,r2);
        strcat(returned,dates);
        strcat(returned,r3);
            strcat(returned,r4);
        strcat(returned,ContentSize);
        strcat(returned,r5);
        strcat(returned,ContentType);
        strcat(returned,r6);

        if(isGet=0)
        {
                strcat(returned,r7);
                strcat(returned,r8);
                    strcat(returned,FileName);
                    strcat(returned,r9);
        }
        if(isGet=1)
        {
                fin=open(pname,O_RDONLY);
                frc = read(fin,bufferer,bufsiz);
                strcat(returned,bufferer);
        }       
               
                write(connsock,returned,strlen(returned));

"undefined reference to..." error

by plucesiar at 17:02 PM, 02/06/2010

Hi, I'm working through the 3rd chapter of Thinking in C++ Vol 1 by Bruce Eckel (free online). I am using Code::Blocks as my IDE. I've try searching for this problem through the forum but haven't found a solution; I think it might be a IDE-specific problem.

The undefined reference error pops up when I try to compile Bitwise.cpp, which references printBinary.h which uses a function in printBinary.cpp. All 3 files are located in the same directory (in a folder called "C++" in My Documents).

The error message says "undefined reference to 'printBinary(unsigned char)'

For your convenience, I have pasted the code below:

//: C03:printBinary.h
// Display a byte in binary
void printBinary(const unsigned char val);
///:~

//: C03:printBinary.cpp {O}
#include <iostream>
void printBinary(const unsigned char val) {
  for(int i = 7; i >= 0; i--)
    if(val & (1 << i))
      std::cout << "1";
    else
      std::cout << "0";
} ///:~

//: C03:Bitwise.cpp
//{L} printBinary
// Demonstration of bit manipulation
#include "printBinary.h"
#include <iostream>
using namespace std;

// A macro to save typing:
#define PR(STR, EXPR) \
  cout << STR; printBinary(EXPR); cout << endl; 

int main() {
  unsigned int getval;
  unsigned char a, b;
  cout << "Enter a number between 0 and 255: ";
  cin >> getval; a = getval;
  PR("a in binary: ", a);
  cout << "Enter a number between 0 and 255: ";
  cin >> getval; b = getval;
  PR("b in binary: ", b);
  PR("a | b = ", a | b);
  PR("a & b = ", a & b);
  PR("a ^ b = ", a ^ b);
  PR("~a = ", ~a);
  PR("~b = ", ~b);
  // An interesting bit pattern:
  unsigned char c = 0x5A;
  PR("c in binary: ", c);
  a |= c;
  PR("a |= c; a = ", a);
  b &= c;
  PR("b &= c; b = ", b);
  b ^= a;
  PR("b ^= a; b = ", b);
} ///:~

Any help greatly appreciated =D

A DLL Problem

by Nicholas_Roge at 15:18 PM, 02/06/2010

In the code below, I check if test.dll has been loaded, and it always returns false... I can't figure out what I'm doing wrong. Can anyone give me a hand?

P.S.: I've triple checked that the DLL is in the running directory.

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

typedef int (*AddFunc)(int,int);
typedef void (*FunctionFunc)();

int main()
{
  AddFunc _AddFunc;
  FunctionFunc _FunctionFunc;
  HINSTANCE hInstLibrary = LoadLibrary((LPCTSTR)("test.dll"));

  if (hInstLibrary)
  {
      _AddFunc = (AddFunc)GetProcAddress(hInstLibrary, "Add");
      _FunctionFunc = (FunctionFunc)GetProcAddress(hInstLibrary,
        "Function");

      if (_AddFunc)
      {
        std::cout << "23 = 43 = " << _AddFunc(23, 43) << std::endl;
      }
      if (_FunctionFunc)
      {
        _FunctionFunc();
      }

      FreeLibrary(hInstLibrary);
  }
  else
  {
      std::cout << "DLL Failed To Load!" << std::endl;
  }

  std::cin.get();

  return 0;
}

Code Snippet Short Shuffle for 1D Array using C++

by miteigi-san at 12:13 PM, 02/06/2010

NOTE:
~this code is in c++
~you need not change anything in the code
~the commented lines are there just in case you want to see how the program works in real time - simply uncomment them and run the program, these commented lines are not necessary for the program to work
~code does not swap the characters of the string n times just to randomize
~string contents are shuffled character by character only
~the code is done with Code::Blocks

HOW THE CODE WORKS:
~the program asks user to input a string, then it outputs the shuffled version of the string
1. the program tells the user to enter a string
2. getline(cin,word); saves the string into string variable word
3. the length of the string is determined and saved to int variable x
4. srand is called so that the program will randomize differently for each instance you run the program
5. the while loop does the assigning of characters found in string variable word to temp
6. the resulting string temp is outputted so you can see the result of the shuffle

~further explanation for number 5
for example, you entered "twister"
twister is saved to string variable word
x is given the value of the length of the string variable word, which in this example, is 7 (seven)
in the loop,
temp is the string where we add characters found in string variable word. the character that we will use and copy to temp is determined by the int variable y, which generates a value from 0(zero) to the length of the string variable minus one, which in this instance, is 6. after choosing the character, the character is appended to temp.
the problem now is, we dont want that same character to be used again/selected by the randomized selector y - this problem is solved by the other lines in our program.
the idea is, we remove that chosen character (after appending it to temp) from the original string word, so it would not be chosen again.
we can remove that character by:
1.) cutting the string into three, first part will be from the start of the string to the character before the chosen character, second part will be the chosen character, then the last part will be after the chosen character to the last of the string... after cutting it and saving the first and third(last) parts to new strings, we fuse them into one....or
2.) simply assigning the last character of the string into the place of the chosen character (which will overwrite and delete the chosen character) , then cutting the string from the beginning up to the second-to-the-last part of the string (which will delete the last character of the string - which is okay since we moved it to the chosen character's place already)
after that, you see, we don't have the chosen character anymore, we have the last character of the string on it, and the length of the string decreased by one.
the loop then continues until all of the characters from string variable word is gone.

INPUT RESTRICTIONS:
~actually from what i tested, there are no restrictions for the program input...
~it even accepts strings with spaces
~there are no restrictions for values of the string variable word too.

uhm i think thats all about the code. i don't really know if this kind of code exists some place else other than this post because all i see are either random swapping shufflers or threads that needs help on shuffling. and just so you know, it is me who made this code, so yes its my mistake if ever there is one in the code.

typedef struct etc...

by suncica2222 at 10:55 AM, 02/06/2010

I dont understand this...I see this inside () is struct and BOOL is typedef for int actually ???? ,but what is (WINAPI *_CreateProcess) ?????

its loks like typedef <type><type><list of types> ?????

Can some one explain this?


typedef BOOL (WINAPI *_CreateProcess)(   //BOOL is int???
  LPCTSTR lpApplicationName,
  LPTSTR lpCommandLine,
  LPSECURITY_ATTRIBUTES lpProcessAttributes,
  LPSECURITY_ATTRIBUTES lpThreadAttributes,
  BOOL bInheritHandles,
  DWORD dwCreationFlags,
  LPVOID lpEnvironment,
  LPCTSTR lpCurrentDirectory,
  LPSTARTUPINFO lpStartupInfo,
  LPPROCESS_INFORMATION lpProcessInformation
);

strcat

by sidra 100 at 10:05 AM, 02/06/2010

plz guide me i m having some error at line 28
#include <iostream>
using namespace std;

class str
{
  char s[30];
    public:
          str()
          {
                  strcpy(s,"");
                  }
    string getstring()
          {
            cout<<"enter the sting:";
            cin>>s;
          return s; 
                        }
    void displaystring()
    {
          cout <<"the string is:"<<s<<endl;
          }

                 
                         
                        string operator+= (string &t)
                            {
                                   
                                    strcat(s,s.t);
                                   
                                    return s;
                                    }
                                    };
                                   
                                   
          main()
          {
                    str string1;
                    str string2;
                    string1.getstring();
                    string2.getstring();
                      string1+=string2;
                    string1.displaystring();
                           

}
I have a Panel that holds 200 buttoncontrols. If I for example minimize the Formwindow and maximize the window again,
panel1 that holds the 200 buttoncontrols makes the 200 buttoncontrols to "flicker" for about 2 seconds.

I beleive I have set up code for panel1 that have Doublebuffer = true;
(I run this on computer: 2.2 Ghz Dual core)

I dont know how to make this work correctly because the whole application really flickers all the time ?
Below I have put all declarations that has with panel1 to do to see if it is possible to find the problem.

//panel1 declaration
public ref class DoubleBufferPanel : public Panel 

        public: DoubleBufferPanel(void)   
        {       
            this->SetStyle(ControlStyles::DoubleBuffer |
            ControlStyles::UserPaint  |
            ControlStyles::AllPaintingInWmPaint, true);       
            this->SetStyle(ControlStyles::DoubleBuffer, true);       
            this->UpdateStyles();   
        } 
};


        //private: System::Windows::Forms::Panel^  panel1;
        DoubleBufferPanel^ panel1; //Exchange above line to this line ?


//this->panel1 = (gcnew System::Windows::Forms::Panel());
panel1 = gcnew DoubleBufferPanel(); //Exchange above line to this line ?
this->panel1->SuspendLayout();


        //
        // panel1 (holds 200 buttoncontrols that flickers for 2 seconds)
        //
        this->panel1->BackgroundImage = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"panel1.BackgroundImage")));
        this->panel1->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch;
        this->panel1->Controls->Add(this->linkLabel3);
        this->panel1->Controls->Add(this->linkLabel2);
        this->panel1->Controls->Add(this->button266);

      //200 buttoncontrols here !!!!!!!

        this->panel1->Controls->Add(this->menuStrip1);
        this->panel1->Location = System::Drawing::Point(0, 0);
        this->panel1->Name = L"panel1";
        this->panel1->Size = System::Drawing::Size(854, 537);
        this->panel1->TabIndex = 0;

        //
        // Form2 (Form2 holds the panel)
        //
        this->panel1->ResumeLayout(false);
        this->panel1->PerformLayout();
        this->DoubleBuffered = true;

How to find occurence of a digit in a number.

by hydersha at 05:59 AM, 02/06/2010

hey guys..
greetings to all
please help me regarding my problem
i want to find how many times a digit has occurred in a number.
for example

i have an array which consists of numbers

1011 1022 1033

number of 1's= 5
number of 2's= 2
number of 3's= 2

.. i want to to that .. please help how can i do this.

string to float

by Jeronim at 05:39 AM, 02/06/2010

I have read a lot of topics with these subject many of theme where on these forum but what ever i try i cant get this working.

I have tried 4 or 5 function for converting string to float but i always get compiler error left from xxx must be class/struct ....

here is the function

void calculate(string& part_){
       
        float number_one=0;
        float number_two=0;

        for(int i=0; i<4; ++i){
                for (int j=0; j<part_.length(); ++j){
                        if(part_[j]== '/'){
                       
                                number_one = part_.at(j-1); // need to be converted to float somehow
                                number_two = part_[j+1]; // these too
                                number_one /= number_two;

                                part_[j-1] = number_one;
                                part_.erase(j, j+2);

                               
                       
                        }
                }
        }
}

Use of variables.

by faizanahmedin at 04:57 AM, 02/06/2010

Can a variable declared as public be used in the main function?

Problem with Code::Blocks debugger

by n.utiu at 03:09 AM, 02/06/2010

I have recently installed Code:Blocks 8.02 for Windows, but I have a problem with my debugger. Every time I try to debug I get an error that says I haven't set my debugger executable yet.

I selected the mingw c++ compiler included in the install, and set the debugger exe to the gdb.exe from bin.

Please help! :S

Does class X implement function Y

by CollDet at 02:52 AM, 02/06/2010

Hello.

I'm writing a manager class that should handle a vast and expandable group of classes. The manager class uses a hash_map to store all these etherogenous objects. The objects are all derivations of a base class Object, and of different "interface" classes which are used to define required functions. An example:

class Object{ ... };

class IUpdatable
{
        ...
        public:
                virtual void Update()=0;
        ...
};

So I could have classes that derive from class Object and from class IUpdatable, but that override the Update function in very different ways - or that do not even derive from IUpdatable (meaning that particular type of object requires no update at all after creation).

Now, I can't change this design. So, first I thought to just fill the hash map with pointers to Object, and (continuing with the example above) within the manager Update method, let the polymorphism kick in once I call the Update function of the updatable stored objects, like this:

void Update()
{
        // SHM is the hash map type, s is the hash map instance
        for (SHM::iterator i=s.begin(); i != s.end(); ++i)
        {
                i->second->Update();
        }
}

But obviously I can't do that, since
1. I do not know if the stored object derives from IUpdatable too.
2. Update is not a member of Object (and it makes no sense to have Update defined in Object).

I was thinking that I could just use typeid and confront the type info with all the possible types that derive from that "interface" class, but that's ugly programming imho. Maybe it's possible to check if a class implements a function (and in that case I'd automatically be allowed to cast the object to the IUpdatable type and use polymorphism).

So my question is, is there an elegant way to solve this situation?

getting started

by aman rathi at 23:02 PM, 02/05/2010

hi
as i finished my I sem of computer applications at SGRRITS coll in dehradun ,india in second sem C++ is part of my course.
now i want to know about the main difference between c and c++
how c++ is more use ful and its features with the help of example.
please also explain in brief how above example will executed.

i am a begnner so please....................you know.

Char problem in C++ Calculator

by matharoo at 21:24 PM, 02/05/2010

I am making a scientific calculator as an assignment in my class. I am using switch case for all the operators like +-*/ , and I am calling them with a single keyword like '+' for addition and so on. The problem is that when i try to use more than one word in case statement for mathematical function like Tan, Cos or sin , The program does not calculate anything. I am using char for the cases in switch statement.
here's da snippet of what i am doing (i am showing some part of the program, consider i have already declared all the variables) :

char ch[10];
switch(ch)
        {case 's': // i want to use 'sin' here but the program does not calculate anything after i do so!
                trig= sin(fno*pi/180);
                cout<<endl<<"Sin("<<fno<<") = "<<trig<<endl<<endl;
                break;
        }

Any help will be appreciated... thanks...

Chaining Overloaded Operators

by ms_farenheit1 at 20:21 PM, 02/05/2010

I have been having a lot of trouble getting my overloaded operators to properly with each other, especially in cases such as a=a+b+c
When I execute the program, I get an error: "Unhandled exception at 0x01201f10 in Project1_v3.exe: 0xC0000005: Access violation reading location 0xcccccccc." But I am not sure exactly what that means or where it comes from.
I have posted all relevant code including my test file. I would really appreciate any insights you have about what could be causing this problem.

Implementation file:
#include "matrix.h"

//Constructors

matrix::matrix(int r, int c)
        //create matrix with specified row and column dimensions
{
        try
        {
                if ((r<=0)||(c<=0))
                        throw invalid_argument ("Matrix row and column arguments must be greater than zero.");
        row=r;
        column=c;
        }
        catch (exception & ex)
        {
                cout<<"Error: "<<ex.what()<<endl;
        }

        try
        {
                data=new matrixData * [row];
                for (int i=0; i<row; i++)
                        data[i]=new int [column];
        }
        catch (exception & ex)
        {
                cout<<"Error: "<<ex.what()<<endl;
        }
        fillMatrix();
}
//Destructor
matrix::~matrix ()
{
        for (int i=0; i<row; i++)
                delete [] data[i];
        delete [] data;
}
matrix & matrix::operator=( const matrix & in)
{
        if ((row!=in.getRows())||(column!=in.getColumns()));
        {
                column=in.getColumns();
                row=in.getRows();
        }
        if (!(*this==in))
        {
                for (int i=0; i<row; i++)
                {
                        for (int j=0; j<column; j++)
                                data[i][j]=in.getEntry(i, j);
                }
        }
        return *this;
}

matrix & matrix::operator+=(const matrix & in)
{
        try
        {
                if ((column!=in.getColumns())||(row!=in.getRows()))
                        throw invalid_argument ("Matricies must be of equal size.");
        }
        catch (exception & ex)
        {
                cout<<"Error: "<<ex.what()<<endl;
                return *this;
        }
        for (int i=0; i<row; i++)
        {
                for (int j=0; j<column; j++)
                        this->setEntry(i,j,((data[i][j])+in.getEntry(i,j)));
        }
        return *this;

matrix & matrix::operator+(const matrix & in)
        //Computes and returns the sum of two matricies
{
        return matrix (*this) += in;
}
ostream& operator<<(ostream& output, const matrix & in)
        //print matrix to standard output
{
        for (int i=0; i<in.getRows(); i++)
        {
                output<<endl;
                for (int j=0; j<in.getColumns(); j++)
                {
                        output.width(3);
                        output<<in.getEntry(i,j)<<"  ";
                }
        }
        output<<endl;
        return output;
}

//Helper Functions used to implement matrix class member functions

void matrix::fillMatrix()
{
        for (int i=0; i<row; i++)
        {
                for (int j=0; j<column; j++)
                        data[i][j]=(matrixData) i-j;
        }
}

int matrix::getColumns()const
{
        return column;
}

int matrix::getRows() const
{
        return row;
}

int matrix::getEntry(const int r_index, const int c_index) const
{
        return data[r_index][c_index];
}

void matrix::setEntry (const int r_index, const int c_index, const matrixData value)
{
        data[r_index][c_index]=value;
}

Test File:
int main()
{
  matrix a(3, 4);
  matrix b(3, 4);
  matrix c(4, 4);
  matrix d(4, 4);
  matrix e(4, 4);
  matrix f(4, 4);
  matrix h(4, 4);
 
  if ( a != b )
  {
            cout << "Matrix a and b are not equal" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
  };
           
  e += f;

  cout << "f = " << f << endl;
  cout << "e -= f = " << e << endl;
  f = e = d;
  h = d + e + f; //error.
  cout << "d = " << d << endl;
  cout << "e = " << e << endl;
  cout << "f = " << f << endl;
  cout << "h = " << h << endl;

  if ( h == e ) cout << "Matrix h and e are the same" << endl;
  else
  {
            cout << "Matrix h and e are not equal" << endl;
    cout << "h = " << h << endl;
    cout << "e = " << e << endl;
  }
 
  return 0;
}

pointers to 2d arrays

by SpyrosMet at 18:49 PM, 02/05/2010

Hello. Can someone tell me what will happen if i have an array Ar[5][5] and a pointer ptr = Ar[0][0] and try accessing the second line of Ar throught ptr by increasing it by 5? I mean ptr+5 ==Ar[1][5] or something else?


#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main ()

{
    srand (time(0));
   
    int count = 0;
    int random_num = (rand () % 100) + 1;
    int high_num = random_num;
    int low_num = random_num;
    float total = 0.0;
    while (count < 100000){
       
        count++;

        random_num = (rand () % 100) + 1;
       

           
        if (high_num < random_num)
        high_num = random_num;
       
        if (low_num > random_num)
        low_num = random_num;
       
        total = total + random_num;


}



        float average = total / 100000;
       
        cout << "The high number is: " << high_num << endl;
        cout << "The low number is: " << low_num << endl;
        cout << "The average is: " << average << endl;

system ("Pause");   
return 0;
        }

The program compiles and runs. It generates random numbers, displays the highest and lowest, and the average. I got it to get the highest and lowest numbers by fiddling around with the "if" statement and using the ">" and "<" signs.

Eventually I got it to work after trying combination of numbers and declared int statements and was able to get it to define the high and low numbers correctly.

My question is, how does it work?
        if (high_num < random_num)
        high_num = random_num;
       
        if (low_num > random_num)
        low_num = random_num;

I set them to equal to the random number, which I defined later in my int statements. In the "if" statements, it shows the high number being less than a random number, and if it's true, the high number is equal to a random number.... I just don't get how it'd work. Wouldn't it be a greater than sign, which I've tried. All it does is make the lowest 100 and the highest 0.

Ohkay now I'm rambling. Could someone just tell me how that statement works

Constructor problem

by Jeronim at 17:02 PM, 02/05/2010

hi!

I have created a class with 2 constructors and whenever i try to access it i got the error no match for to call int&

here is the code
class A{
      public:
      A(){};
      A(int i);
     
      int moj_broj;
      };

A::A(int i):moj_broj(i){}

int main()
{
    A something; 
    cout<<"before "<<something.moj_broj<<endl;
    something(5);   
    cout<<"after "<<something.moj_broj<<endl;
}

Convert this C# declaration to C++

by Lukezzz at 16:55 PM, 02/05/2010

I am trying to declare a Doublebuffered panel in C++
I can only find the declaration for this in C#.

So I wonder how this could be converted to C++ ?
public class DoubleBufferPanel : Panel
{
    public DoubleBufferPanel()
    {
        // Set the value of the double-buffering style bits to true.



        this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint |
                      ControlStyles.AllPaintingInWmPaint, true);

        this.UpdateStyles();
    }
}

C++ newbie need help...please

by mo94015 at 16:10 PM, 02/05/2010

need to change this from availcredit01.cpp to availseats01.cpp and make the necessary adjustments
1)ask user to enter the room size
2)get room size
3)ask user to enter number of students
4)get enrolled
5)set avilseats to room size minus enrolled
6)display the available sets
7)halt and return to operating system
i'm a newb so any help would be greatly appreciated
#include <iostream>                    // systems-supplied hdrs
#include <cstdio>                      // scanf and printf
using    namespace std;                // avoid std::cin ...

int      main    (void)              // main returns an int
{
        /* main local space  */
        double  balance;            // input variables
        double  creditLimit;        //

        double  availCredit;        // output variable

        /* begin procedural code */
        cout << "Enter balance: ";      // prompt user
        cin >> balance;                  // get data
        cout << "Enter credit limit: ";  // prompt user
        cin >> creditLimit;              // get data

        /* processs input */
        availCredit = creditLimit - balance; // expression

        /* display output */
        printf("\nAvailable Credit: %.2f\n\n", availCredit);

        /* halt and return to operating system */
        return(0);                    // pass int back to o/s
}

/*

Enter balance: 500.00            <- Soft-copy Output
Enter credit limit: 3500.00

Available credit: 3000.00        <- Note rounded result

*/

undefined class errors

by tomtetlaw at 15:59 PM, 02/05/2010

when i run my code, i get lots of undefined class errors, even though i have defined and included the files properly(i think).

here are the errors i'm getting:
------ Build started: Project: engine, Configuration: Debug Win32 ------
Compiling...
baseentity.cpp
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\globals.h(13) : error C2079: 'CGlobals::controller' uses undefined class 'CEntityController'
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\baseentity.cpp(9) : error C2228: left of '.AddEntity' must have class/struct/union
type is 'int'
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\baseentity.cpp(59) : warning C4244: 'argument' : conversion from 'double' to 'float', possible loss of data
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\baseentity.cpp(60) : warning C4244: 'argument' : conversion from 'double' to 'float', possible loss of data
main.cpp
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\globals.h(13) : error C2079: 'CGlobals::controller' uses undefined class 'CEntityController'
entitycontroller.cpp
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\globals.h(13) : error C2079: 'CGlobals::controller' uses undefined class 'CEntityController'
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\entitycontroller.cpp(7) : warning C4018: '<' : signed/unsigned mismatch
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\entitycontroller.cpp(13) : warning C4018: '<' : signed/unsigned mismatch
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\entitycontroller.cpp(19) : warning C4018: '<' : signed/unsigned mismatch
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\entitycontroller.cpp(28) : warning C4018: '<' : signed/unsigned mismatch
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\entitycontroller.cpp(45) : warning C4244: 'argument' : conversion from 'double' to 'clock_t', possible loss of data
c:\documents and settings\tom\my documents\visual studio 2008\projects\engine\engine\entitycontroller.cpp(46) : warning C4305: '+=' : truncation from 'double' to 'float'
Generating Code...
Build log was saved at "file://c:\Documents and Settings\tom\My Documents\Visual Studio 2008\Projects\engine\engine\Debug\BuildLog.htm"
engine - 4 error(s), 8 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========



and this is the relevant code:
globals.h:
#ifndef GLOBALS_H
#define GLOBALS_H

#include "timer.h"
#include "id_manager.h"

class CEntityController;

struct CGlobals{
        float curtime;
        CTimer timer;
        IDM id_manager;
        CEntityController controller;
}*gpGlobals;

#endif //GLOBALS_H


entitycontroller.h:
#ifndef ENTITYCONTROLLER_H
#define ENTITYCONTROLLER_H

#include <vector>
#include "globals.h"

class CBase;
class CEntityController{
        std::vector<CBase*> m_vEntities;
        float m_fNextUpdateTime;
public:
        void SpawnEntities( );
        void ActivateEntities( );
        void ThinkEntities( );
        void DeleteEntities( );

        void Start( );
        void Loop( );
        void End( );

        void AddEntity( CBase *pEntity );
};

#endif //ENTITYCONTROLLER_H

any help would be appreciated

error C2676

by clayton797 at 14:49 PM, 02/05/2010

I've been trying to fix this error for a while now, I could really use some help.

C:\Users\Clayton\Documents\CH4P11.CPP(71) : error C2676: binary '>>' : 'class std::basic_ostream<char,struct std::char_traits<char> >' does not define this operator or a conversion to a type acceptable to the predefined operator


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


int main()
{

double baseSalary;
double noOfServiceYears;
double bonus;
double totalSale;
double additionalBonus;
double payCheck;


cout<<fixed<<showpoint;
cout<<setprecision(2);

cout<<"To calculate the salesperson's paycheck, please enter all data"
<<" as accurately as possible."<<endl;


cout<<"Please enter the base salary."<<endl;
cin>>baseSalary;

cout<<"Please enter the number of years that the salesperson has been"
<<" with the company."<<endl;
cin>>noOfServiceYears;

if(noOfServiceYears <= 5)

bonus = 10 * noOfServiceYears;

else

bonus = 20 * noOfServiceYears;



cout<<"Finally, please enter the total sale made by the salesperson"
<<" for the month."<<endl;
cin>>totalSale;

if(totalSale < 5000)

additionalBonus = 0;

else

if(totalSale >= 5000 && totalSale < 10000)

additionalBonus = totalSale * (0.03);


else

additionalBonus = totalSale * (0.06);


payCheck = baseSalary + bonus + additionalBonus;

cout<<"The paycheck for the salesperson will be approximately ">>payCheck>>" "
<<" . Thank you for using this program."<<endl;

return 0;
}

declaration error

by esesili at 13:56 PM, 02/05/2010

Hi All,
When I try to compile the code below, I get error message " error: ‘MAX_IMG_HEIGHT’ undeclared here (not in a function)". I tried to declare them in different ways but it does not work. Does anyone have idea ?
I appreciate for helps,

The code is:
/* ImagExper.h 

  - miscellaneous structure header file for ImagExpert software package  */



/* image processing range deifnition */



#define top_left_x 20

#define top_left_y 280

#define bottom_right_x 460

#define bottom_right_y 500



/* edge element gradient magnititue and direction */


//extern const int MAX_IMG_HEIGHT;
//extern const int MAX_IMG_WIDTH;

unsigned char img_edg_mag[MAX_IMG_HEIGHT][MAX_IMG_WIDTH];

unsigned char img_edg_dir[MAX_IMG_HEIGHT][MAX_IMG_WIDTH];



/* External variables for hough transfer function */



/*#define PI 3.1415926*/



struct edge {                            /* edge struct pointer */

          int xcord;  int ycord;

          unsigned char edgv;            /* grey level or gradient */

          int edsi;                      /* 360 degree */

          };



struct peak_point{                      /* hough space peak point */

          int sita;

          int rota;

          int ctva;

          };





/* Functions for Hough transfer */



void edsobl(int k, unsigned char* pie0,int ixsa,int iysa,int ixea,int iyea,

            int ity,int thres_gr);

void thingr(int k,unsigned char *pie0,int ixsa,int iysa,int ixea,int iyea,

            long int *nu_edge);

void edggen(int k,unsigned char *pie0,int ixsa,int iysa,int ixea,int iyea,

      struct edge *pedge0);

void edhou1(int k,struct edge *pedge0,long int nu_edge,

      int ixsa,int iysa,int ixea,int iyea,int *ixs_next,int *iys_next);



void hlndsp(int k, float deta_ro,float deta_si,float roc,int ix,int iy,

            float x0,float y0,int ixsa,int iysa,int ixea,int iyea,

            struct peak_point *peakpt0,long int nu_peakpt,

            int *ixs_next,int *iys_next);



void pkptds(int *ht0,int ia,int ir,struct peak_point *peakpt0,

            long int *nu_peakpt);

void pkptdp(int *ht0,int ia,int ir,struct peak_point *peakpt0,

            long int *nu_peakpt);





/* Function definition */



void GSRoadSection(int ixs,int iys,float alfa,int lsgn,int length,int width,

                  unsigned char *imask, int k);

pointer initialization

by mmasny at 13:52 PM, 02/05/2010

Hello, I'm not much of a programmer and will probably never be, but am just curious.
Can I initialize a pointer with a constant value different than NULL? I.e. can I tell my pointer to point at one particular memory cell? It's a number so why couldn't I? I know it would be of little use in normal programming, but I thought it could be could good while programming some devices with very little memory, where one would like to control every cell.

capturing enter key event in c++

by mimran at 12:22 PM, 02/05/2010

hi can some one help me
I want to take url name in textbox from user and when he press enter key that url should open.
I want code of this program in c++ visual studio 2008.

syntax error 2143

by timbomo at 11:57 AM, 02/05/2010

and this what is a better way too write this without getting an error

if ((symb1 != 'A', 'a') || (symb2 != 'B', 'b') || (symb3 != 'C', 'c') || (symb4 != 'D', 'd'));; << endl;

{
cout << "Please enter an corresponding letter." << endl;
}

and this what is a better way too write this without getting an error

while ((symb1 != 'A', 'a') || (symb2 != 'B', 'b') || (symb3 != 'C', 'c') || (symb4 != 'D', 'd'));; >> endl;

{
cout << "Wrong" << endl;
<< "Enter one of the four letters.\n" ;
cin >> symb1 >> symb2 >> symb3 >> symb4;
}
else
cout << "You have chosen" << symb << endl;

and this is my program and i cant run it without errors, its 4 school so could u give me advise so i will know in the future

#include<iostream>
#include<string>
using namespace std;
int main()
{
char symb1, symb2, symb3, symb4;
int item_purch, numb_item_purch, quit;
double mug, tee_shirt, pen,tot_mon, curr_cash, mon_spent;

cout << "So what do you want to purchase today?\n";
symb1=('A','a');
symb2=('B','b');
symb3=('C','c');
symb4=('D','d');
cout << symb1 << " Mug" << mug << endl;
cout << symb2 << " Tee Shirt " << tee_shirt << endl;
cout << symb3 << " Pen " << pen << endl;
cout << symb4 << " Quit " << quit << endl;
mug = 2.50;
tee_shirt = 9.50;
pen = .75;
if ((symb1 != 'A', 'a') || (symb2 != 'B', 'b') || (symb3 != 'C', 'c') || (symb4 != 'D', 'd'));; << endl;

{
cout << "Please enter an corresponding letter." << endl;
}
else
cout << "You have chosen" << symb << endl;

cin >> symb1;
cin >> symb2;
cin >> symb3;
cin >> symb4;
cout << "You have a total of 30 dollars.\n";
cin >> tot_mon;
tot_mon = 30;
cout << "Please pick a letter that corresponds with the merchandice of your choosing.\n";\

while ((symb1 != 'A', 'a') || (symb2 != 'B', 'b') || (symb3 != 'C', 'c') || (symb4 != 'D', 'd'));; >> endl;

{
cout << "Wrong" << endl;
<< "Enter one of the four letters.\n" ;
cin >> symb1 >> symb2 >> symb3 >> symb4;
}
}

return 0;
}

printing out shapes in c++

by Jfunch at 11:32 AM, 02/05/2010

Hi i'm writing this program where the user chooses whether to print out a square, a forward triangle, and a backwards triangle using the "*" character. I got the square and the backwards triangle to work and the forward triangle, but i cant figure out how to do the back wards one.
*
**
***
**** is how the foward triangle looks when the user enters the size of 4 the backwards one should look like

*
**
***
**** when the user enters 4 for the size. my code for the normal triangle is below(for some reason this wont show up how its suppose to but it should look the same as the normal triangle just slanting to the left instead of to the right.)
cout << "enter the size of your triangle." << endl;
cin >> size;

for(line = 1;line <= size; line++)
{
stars = line;
for(loop = 1;loop <= stars;loop++)
{
cout << "*";
}
cout << endl;
}


If anyone could help me to print out the backwards triangle with just if -else statements and loops that would be great.

passing an array of pointers to objects as parameter C++

by SpyrosMet at 11:27 AM, 02/05/2010

Hello. I need an example of how to pass an array of pointers to objects as a parameter to a function or a constructor. It's urgent. Please help me. Thank you.

compound assignment operator

by sidra 100 at 11:12 AM, 02/05/2010

plz chk i want to overload compound assignment operator bt its gving me some error
#include <iostream>
using namespace std;

class strng
{
  char s[30];
    public:
          strng()
          {
                  strcpy(s,"");
                  }
                    void getstring()
                  {
                        cout<<"enter the sting:";
                        cin>>s;
                        }
                        void displaystring()
                        {
                            cout <<"the string is:"<<s<<endl;
                            }

                 
                  string operator +=(string &t);
                  };
                 
                        string strng:: operator +=(string &t)
                            {
                                    strng str;
                                    strcpy (str.s,"");
                                    strcat (str.s,s);
                                    strcat (str.s,s.t);
                                    return s;}
                                    main
                                    {
                                        string string1;
                                        string string2;
                                        string1.getstring();
                                        string2.getstring();
                                        string string1=string1+string2;
                                        string1.displaystring();
                           

}

no memory to process 1Gb file? string bad allocation

by tetron at 09:16 AM, 02/05/2010

I am having problems with the new operator() specifically within
std::string

I appear to have hit a memory limit in visual studio.

Ideally I would like someone to help me find one of the following solutions:

1 - Can I access the memory in a very big file directly without a memory buffer?
2 - How do you increase the maximum size of the free store in visual studio?

My approach at the moment is not working I have a very big file that I want to
chop before processing.

- I create a membuffer for a 1Gb file (this was made from 25Gb file)
- then try to use a std::string to iterate over the string.

but I cannnot create the string as I get
bad allocation error
from cstr()

A simplified version of my code

#include <string>
#include <exception>
#include <fstream>
#include <iostream>

void main()
{

 std::ifstream fin("D:\\Gig1.txt", std::ios::in);
 if(fin.is_open)
 {
  unsigned int sz(1073741825); // 1 gig (1024)^3
  char * memblock = new char[sz]; //this is fine
  //check file sz is right size not called as sz == gcount
  fin.seekg(0, std::ios::beg);
  fin.read(memblock, sz);
  if(sz > fin.gcount())
  {
    sz = fin.gcount();
  }

  try
  {
        std::string str(memblock, sz); //too much for visio :(
  }
  catch(exception &e)
  {
  std::cout << e.what() << std::endl;
  }

  delete [] memblock;
  fin.close();
 }


}

This is an approximate code and I am posting here as my first post was asking the wrong question.

Thanks,
David

How to Create an Expression Evaluator in C++

by arithehun at 08:37 AM, 02/05/2010

I am trying to create an expression evaluator to expand my C++ knowledge. It is supposed to evaluate 5(x+7)-2. Here is the code:

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

using namespace std;

time_t now, later;

void sleep(int delay)
{
 now=time(NULL);
 later=now+delay;
 while(now<=later)now=time(NULL);
}

int main(void){
    //It finds an error here 
  int x, 5, 7, 2, total;
  printf("Hello. This program will evaluate the expression 5(x+7)-2. \nEnter the value for x:");
  //And here
  total= 5(x+7)-2;
  cin >> x;
  cout << total << endl;
  getchar();
  return 0;}
I know it contains many errors; can someone tell me what I should do?

Thanks a lot!!!
2008 scandalz.net
They told me you had proven it When they discovered our results About a month before. Their hair began to curl The proof was valid, more or less Instead of understanding it But rather less than more. We'd run the thing through PRL. He sent them word that we would try Don't tell a soul about all this To pass where they had failed For it must ever be And after we were done, to them A secret, kept from all the rest The new proof would be mailed. Between yourself and me. My notion was to start again Ignoring all they'd done We quickly turned it into code To see if it would run.
CountryUS
IP Address38.107.191.99
User AgentCCBot/1.0 (+http://www.commoncrawl.org/bot.html)