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.

c++ and libcurl: fopen as a function cause an error

by Rishikeshan at 00:32 AM, 09/03/2010

Mingw shows
----- CurlT ( MAIN GCC DEBUG DEBUG_FULL BLITZ WIN32 )
curl.cpp
C:\MyApps\CurlT\curl.cpp: In function 'void* getfile(std::string, char*)':
C:\MyApps\CurlT\curl.cpp:39: warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime
C:\MyApps\CurlT\curl.cpp: In function 'int main()':
C:\MyApps\CurlT\curl.cpp:57: warning: deprecated conversion from string constant to 'char*'
CurlT: 1 file(s) built in (0:01.68), 1688 msecs / file, duration = 1703 msecs, parallelization 0%
Linking...
C:\upp\out\MINGW.Debug.Debug_full\CurlT.exe (1324179 B) linked in (0:00.67)

OK. (0:02.40)
HELP ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

#include <curl/curl.h>
#include <curl/easy.h>
#include <iostream>
#include <stdio.h>
#include <String>
using namespace std;
void funct(string, char*);

size_t my_write_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
  return fwrite(ptr, size, nmemb, stream);
}
 
size_t my_read_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
  return fread(ptr, size, nmemb, stream);
}
int my_progress_func(string *te,
                    double t,
                    double d,
                    double ultotal,
                    double ulnow)
{
  cout<<d*100.0/t<<endl;;
  return 0;
}

void *getfile(string url, char *file)
{
  CURL *curl;
  CURLcode res;
  FILE *outfile;
 
  curl = curl_easy_init();
  if(curl)
  {
    outfile = fopen(file, "w");
 
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_func);
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, my_read_func);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
    curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func);
 
    res = curl_easy_perform(curl);
 
    fclose(outfile);
    /* always cleanup */
    curl_easy_cleanup(curl);
  }
 
  return NULL;
}

int main(){
getfile("http://www.bing.com", "f.out");
}

Serialization

by ganesh_IT at 23:49 PM, 09/02/2010

what is data Serialization in MFC framework

static cast Problem , help plz :)

by medopunsher at 20:12 PM, 09/02/2010

Hey everybody ,
I'am writing a very simple chat program (Client & Server) in C++ & QTNetwork libary.
I Have a static cast problem that i don't understand , here is my code :

PS.Lines with errors are commented :

#include "server.h"
#include "ui_server.h"
#include <QtNetwork/QTcpSocket>
Server::Server(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Server)
{
    ui->setupUi(this);
    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any,quint16(7676));
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(Client()));
}

Server::~Server()
{
    delete ui;
    tcpServer->close();
}

void Server::Log(QString toLog)
{
    ui->plainTextEdit->appendPlainText(toLog+"\n");
}

void Server::ClientDisconnected()
{
    QString msg = "Disconnected Client : ";
    QTcpSocket *tmp = static_cast<QTcpSocket*>(sender); //PROBLEM HERE
    msg += tmp->peerAddress().toString();
    Log(msg);
    clients.removeAll(tmp);
}

void Server::BroadcastMessege(QString msg)
{
    for(int i=0;i<clients.length();i++)
    {
        QTextStream stream(clients[i]);
        stream << msg << endl;
    }
}

void Server::ReadClient()
{
    QTcpSocket* tmp = static_cast<QTcpSocket*>(sender); // PROBLEM HERE
    QString readdata;
    while(tmp->canReadLine())
    readdata += tmp->readLine();
    Log("Messege : "+readdata);
}

void Server::Client()
{
    QString msg = "New Connection From : ";
    QTcpSocket *ss = tcpServer->nextPendingConnection();
    QHostAddress cAd = ss->peerAddress();
    msg += cAd.toString();
    Log(msg);
    clients.append(ss);
    connect(ss,SIGNAL(disconnected()),this,SLOT(ClientDisconnected()));
    connect(ss,SIGNAL(readyRead()),this,SLOT(ReadClient()));
}

The error code is the same for both problems , here it is :

error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘QTcpSocket*’

Any help would be greatly appreciated.
Thanks. :)

Grading exams project

by jelinky at 18:53 PM, 09/02/2010

this is the exact instructions:

"The program will grade a series of exams and then print a grade report for students in a course.

Input: An instructor has a class of students each of whom takes a multiple-choice exam with 10 questions. For each student in the class, there is one line in the input file. The line contains the answers that student gave for the exam. The input file named "grade_data.txt" will have the following format:

line 1: the key for the exam (e.g.)

bccbbadbca

lines 2-n:

a set of answers. You know you are done when you get to a line with no data.
Note: You will not know in advance how many exams you have to grade and you don't need to store the exam answers in your program.

Processing: The program is to read the input file and grade each exam and print out the score for that exam.

Output: Here is an example of how the output might appear. You will write the report to an output file named "grade_report.txt"

student 1 - 8
student 2 - 10
student 3 - 1
etc.

Final Report
------------

10 - 4
9 - 2
8 - 3
.
.
1 - 3
0 - 0

high score - 10

low score - 1

mean score - 6.25"


ive done a lot of it so far but i cant figure out how to do a few things. I cant figure out how to list how many people got question 1 right, question 2 right, etc. and im having trouble finding the highest/lowest/ and mean scores.

i didnt use any arrays on this project, and im not sure if it would be better to use an array for this kind of thing or if i can still make it work without any arrays.

this is the code i have so far:

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

ifstream infile("grade_data.txt");
string grades, key;
string t1;
int temp;

int main()
{
            if (!infile)
{
                        cout << "Error opening file\n\n";
                        system("pause");
}
        else
                cout << "File Successfully Opened\n\n";
               
               
                infile >> key;
               
                string a1 = key.substr(0,1);
            string a2 = key.substr(1,1);
            string a3 = key.substr(2,1);
            string a4 = key.substr(3,1);
            string a5 = key.substr(4,1);
            string a6 = key.substr(5,1);
            string a7 = key.substr(6,1);
            string a8 = key.substr(7,1);
            string a9 = key.substr(8,1);
            string a10 = key.substr(9,1);
           
               
            cout<<endl;
           
            infile >> grades;
            while (!infile.eof())
{
            temp++;
           
           
            string b1 = grades.substr(0,1);
            string b2 = grades.substr(1,1);
            string b3 = grades.substr(2,1);
            string b4 = grades.substr(3,1);
            string b5 = grades.substr(4,1);
            string b6 = grades.substr(5,1);
            string b7 = grades.substr(6,1);
            string b8 = grades.substr(7,1);
            string b9 = grades.substr(8,1);
            string b10 = grades.substr(9,1);
           
            int results=0;
           
            if (a1==b1)
            results++;
            if (a2==b2)
            results++;
            if (a3==b3)
            results++;
            if (a4==b4)
            results++;
            if (a5==b5)
            results++;
            if (a6==b6)
            results++;
            if (a7==b7)
            results++;
            if (a8==b8)
            results++;
            if (a9==b9)
            results++;
            if (a10==b10)
            results++;
           

            int g;
            g=results*10;
            cout<<"Student "<<temp<<":    Made: "<<results<<"  Missed: "<<10-results<<"  Grade: "<<g<<"%\n";
            infile >> grades;           
                 
}
           
           
           

cout<<endl;
system("pause");
}

OpenGL help

by koolman123 at 18:04 PM, 09/02/2010

Hey, at my camp, I made a random 3D maze gen off of OpenGL

So, I downloaded OpenGL 3.7, and I placed the glut.dll in the right place, the header file in the right place, the lib file in the right place etc.

But my conflict is that I used a different version of OpenGL at my camp because the header 3.7 header doesn't recognize some of the code.

So could someone tell me what version of OpenGL uses this header?

<GL/glut.h>
thank you.

And if you know the solution and can run the code, here is the whole code if you're curious.

// openGL stuff 

#include <list>
#include <time.h>
#include <windows.h>
#include <GL/glut.h>
#include <stdlib.h>
#include <cstdio>
#include <iostream>

#define MSIZE 5

using namespace std;

void init();
void display();
void keyboard();

class Character {
GLfloat x, y, z;

public:
        Character(GLfloat _cx, GLfloat _cy, GLfloat _cz)
        {
        x = _cx;
        y = _cy;
        z = _cz;
        }
        Character(const Character& b)
        {
        x = b.x;
        y = b.y;
        z = b.z;
        }

        void draw()
        {
        glShadeModel(GL_SMOOTH);
        glPushMatrix();
        //glRotatef(cspin, 0.0, 0.0, 1.0);
        //cspin ++;
        glTranslatef(0.0, 0.0, -.25);
        glColor4f(1.0, 0.0, 1.0, 0.0);
        glutSolidTeapot(5.0);
        glDisable(GL_LIGHTING);
        glPopMatrix();
        }
};

class Cell {

public:
        GLfloat x, y, z;
        GLfloat width, depth, height;
        GLfloat red, green, blue;

        Cell(){
                x = -1;
                y = -1;
                z = -1;
                red = ((float) rand()) / RAND_MAX;
                green = ((float) rand()) / RAND_MAX;
                blue = ((float) rand()) / RAND_MAX;
        }

        Cell(const Cell& cell){
                x=cell.x;
                y=cell.y;
                z=cell.z;
                red = cell.red;
                green = cell.green;
                blue = cell.blue;

        }

        bool adjacent(Cell& cell)
        {
                GLfloat dx = abs(x-cell.x);
                GLfloat dy = abs(y-cell.y);
                GLfloat dz = abs(z-cell.z);

                return (dx == 1 && dy == 0 && dz == 0) ||
                          (dy == 1 && dx == 0 && dz == 0) ||
                          (dz == 1 && dx == 0 && dy == 0);
        }

        bool equals (Cell& cell)
        {
                return(x==cell.x && y == cell.y && z == cell.z);
        }

        void draw()             
        {
                /*glFrontFace(GL_CW);
                glBegin(GL_QUADS);
                glColor4f(0.0, 1.0, 1.0, 0.7);
                glVertex3f(x, y, z);
                glVertex3f(x + width, y, z);
                glVertex3f(x + width, y + height, z);
                glVertex3f(x, y + height, z);
               
                glColor4f(1.0, 0.0, 0.0, 0.7);
                glVertex3f(x, y, z);
                glVertex3f(x, y + height, z);
                glVertex3f(x, y + height, z + depth);
                glVertex3f(x, y, z + depth);
               
                glColor4f(1.0, 1.0, 0.0, 0.7);
                glVertex3f(x, y, z);
                glVertex3f(x, y, z + depth);
                glVertex3f(x + width, y, z + depth);
                glVertex3f(x + width, y, z);
               
                glColor4f(0.0, 1.0, 1.0, 0.7);
                glVertex3f(x + width, y + height, z + depth);
                glVertex3f(x + width, y, z + depth);
                glVertex3f(x, y, z + depth);
                glVertex3f(x, y + height, z + depth);
               
                glColor4f(1.0, 0.0, 0.0, 0.7);
                glVertex3f(x + width, y, z + depth);
                glVertex3f(x + width, y + height, z + depth);
                glVertex3f(x + width, y + height, z);
                glVertex3f(x + width, y, z);
               
                glColor4f(1.0, 1.0, 0.0, 0.7);
                glVertex3f(x + width, y + height, z);
                glVertex3f(x + width, y + height, z + depth);
                glVertex3f(x, y + height, z + depth);
                glVertex3f(x, y + height, z);
               
                glEnd();*/
               
        }
       
        //int operator<(Cell& );
};


typedef list<Cell> CLIST;

class CellSet{
        //CLIST set;

public:
        CLIST set;

        CellSet(){}
        CellSet(Cell cell) {
                set.push_front(cell);
        }
        CellSet(const CellSet& set2){
                set.assign(set2.set.begin(),set2.set.end());
        }
       
        bool member(Cell& cell){
                for(CLIST::iterator i=set.begin();i!=set.end();++i) {
                        if (cell.equals(*i)){
                                return true;
                        }
                }
                return false;
        }

        CellSet& merge(CellSet& set2)
        {
                //se
                for(CLIST::iterator i=set2.set.begin();i!=set2.set.end();++i) {
                        CLIST::iterator j=set.begin();
                        if (!member(*i))
                        {
                                set.push_front(*i);
                        }
                }
                return *this;
        }
        CellSet& difference(CellSet& set2)
        {
                for(CLIST::iterator i=set2.set.begin();i!=set2.set.end();++i) {
                        CLIST::iterator j=set.begin();
                        while (j!=set.end()&& !(*i).equals(*j)) {
                                ++j;
                        }
                        if(j!=set.end())
                        {
                                set.erase(j);
                        }
                }
                return *this;
        }
        bool empty(){
                return set.empty();
        }
        CellSet& intersect(CellSet& set2){
                for(CLIST::iterator i=set.begin();i!=set.end();++i) {
                        CLIST::iterator j=set2.set.begin();
                        while (j!=set2.set.end()&& !(*i).equals(*j)) {
                                ++j;
                        }
                        if(j==set2.set.end())
                        {
                                set.erase(i);
                        }
                }
                return *this;
        }
        bool subset(CellSet& set2){
                CLIST::iterator i;
                for(i=set.begin();i!=set.end();++i) {
                        if (! set2.member(*i)){
                                return false;
                        }
                }
                return true;
        }
        bool equals(CellSet& set2){
                CLIST::iterator i;
                return (subset(set2) && set2.subset(*this));
        }


        CLIST::iterator get(int index){
                CLIST::iterator i;
                for (i=set.begin();index > 0 && i != set.end();++i, --index);
                return i;
        }
};

typedef list<CellSet> CSLIST;

class CSSet {
        //CSLIST set;

public:
        CSLIST set;

        CSSet(){}
        CSSet(CellSet cell) {
                set.push_front(cell);
        }
        CSSet(const CSSet& set2){
                set.assign(set2.set.begin(),set2.set.end());
        }
       
        bool member(CellSet& cell){
                for(CSLIST::iterator i=set.begin();i!=set.end();++i) {
                        if (cell.equals(*i)){
                                return true;
                        }
                }
                return false;
        }

        CSSet& merge(CSSet& set2)
        {
                //se
                for(CSLIST::iterator i=set2.set.begin();i!=set2.set.end();++i) {
                        CSLIST::iterator j=set.begin();
                        if (!member(*i))
                        {
                                set.push_front(*i);
                        }
                }
                return *this;
        }
        CSSet& difference(CSSet& set2)
        {
                for(CSLIST::iterator i=set2.set.begin();i!=set2.set.end();++i) {
                        CSLIST::iterator j=set.begin();
                        while (j!=set.end()&& !(*i).equals(*j)) {
                                ++j;
                        }
                        if(j!=set.end())
                        {
                                set.erase(j);
                        }
                }
                return *this;
        }
        bool empty(){
                return set.empty();
        }
        CSSet& intersect(CSSet& set2){
                for(CSLIST::iterator i=set.begin();i!=set.end();++i) {
                        CSLIST::iterator j=set2.set.begin();
                        while (j!=set2.set.end()&& !(*i).equals(*j)) {
                                ++j;
                        }
                        if(j==set2.set.end())
                        {
                                set.erase(i);
                        }
                }
                return *this;
        }

        bool subset(CSSet& set2){
                CSLIST::iterator i;
                for(i=set.begin();i!=set.end();++i) {
                        if (! set2.member(*i)){
                                return false;
                        }
                }
                return true;
        }
        bool equals(CSSet& set2){
                CSLIST::iterator i;
                return (subset(set2) && set2.subset(*this));
        }

        CSLIST::iterator get(int index){
                CSLIST::iterator i;
                for (i=set.begin();index > 0 && i != set.end();++i, --index);
                return i;
        }
};

/*int operator<(Cell& cell1, Cell& cell2) {
        return cell1.getID() < cell2.getID();
}*/

//typedef list<CSET> CSSET;

CSSet walls;
GLfloat cspin = 0.0;
GLfloat x = 0.25, y = 0.25, z = 0.25;
GLfloat xspin = 0.0, yspin = 0.0, zspin = 0.0;

CellSet maze;
//Cell cells[MSIZE][MSIZE][MSIZE];
bool intersectWall(CellSet wall) {
Cell cell1 = *(wall.get(0));
        Cell cell2 = *(wall.get(1));
        GLfloat cx = cell1.x, cy = cell1.y, cz = cell1.z;
        //
        GLfloat dx = 1, dy = 1, dz = 1;
        if (cell1.x != cell2.x){
                dx=0;
                cx += (cell1.x < cell2.x ? 1 : 0);
        }               
        if (cell1.y != cell2.y){
                dy=0;
                cy += (cell1.y < cell2.y ? 1 : 0);
        }
        if (cell1.z != cell2.z){
                dz=0;
                cz += (cell1.z < cell2.z ? 1 : 0);
        }
        //
        GLfloat px = x - 0.05, py = y - 0.05, pz = z - 0.05;
        GLfloat pw = 0.1, ph = 0.1, pd = 0.1;

        // x1 = cx, y1 = cy, z1 = cz, width1 = dx, height1 = dy, depth1 = dz
        // x2 = px, y2 = cy, z2 = cz, width2 = pw, height2 = ph, depth2 = pz

        return !(cx>px+pw || cx + dx<px)&&
        !(cy>py+ph || cy + dy<py)&&
        !(cz>pz+pd || cz + dz<pz);

        //glFrontFace(GL_CW);
        //cout << cx << endl;
       
        //glBegin(GL_QUADS);
                //glColor3f(1.0, 1.0, 1.0);
        /*if (dz == 0 || dy == 0) {
                glVertex3f(cx, cy, cz);
                glVertex3f(cx + dx, cy, cz);
                glVertex3f(cx + dx, cy + dy, cz + dz);
                glVertex3f(cx, cy + dy, cz + dz);
        }
       
        if (dx == 0) {
                glVertex3f(cx, cy, cz);
                glVertex3f(cx + dx, cy + dy, cz);
                glVertex3f(cx + dx, cy + dy, cz + dz);
                glVertex3f(cx, cy, cz + dz);
        }*/
        //glEnd();
}

void drawWall(CellSet wall) {
        Cell cell1 = *(wall.get(0));
        Cell cell2 = *(wall.get(1));
        GLfloat cx = cell1.x, cy = cell1.y, cz = cell1.z;
        //
        GLfloat dx = 1, dy = 1, dz = 1;
        if (cell1.x != cell2.x){
                dx=0;
                cx += (cell1.x < cell2.x ? 1 : 0);
        }               
        if (cell1.y != cell2.y){
                dy=0;
                cy += (cell1.y < cell2.y ? 1 : 0);
        }
        if (cell1.z != cell2.z){
                dz=0;
                cz += (cell1.z < cell2.z ? 1 : 0);
        }

        //glFrontFace(GL_CW);
        //cout << cx << endl;
        glColor3f((cell1.red + cell2.red) / 2,(cell1.green + cell2.green) / 2, (cell1.blue + cell2.blue) / 2);
        /*glBegin(GL_QUADS);
                glVertex3f(-1.0, -1.0, -1.0);
                glVertex3f(-1.0, 1.0, -1.0);
                glVertex3f(1.0, 1.0, -1.0);
                glVertex3f(-1.0, 1.0, -1.0);
        glEnd();*/
        glBegin(GL_QUADS);
                //glColor3f(1.0, 1.0, 1.0);
        if (dz == 0 || dy == 0) {
                glVertex3f(cx, cy, cz);
                glVertex3f(cx + dx, cy, cz);
                glVertex3f(cx + dx, cy + dy, cz + dz);
                glVertex3f(cx, cy + dy, cz + dz);
        }
       
        if (dx == 0) {
                glVertex3f(cx, cy, cz);
                glVertex3f(cx, cy + dy, cz);
                glVertex3f(cx, cy + dy, cz + dz);
                glVertex3f(cx, cy, cz + dz);
        }
        glEnd();

}



/*        W                x,y,z        W
        0,1,1        1,1,1        1,1,1

        xy walls
        xz walls
        yz walls
*/



GLfloat tx = 0.0, ty = 0.0, tz = 0.0;
GLfloat cx = 0.0, cy = 0.0, cz = -10.0;
/*typedef list<Building> BLIST;

BLIST bl;*/

/*void draw()
{
        glShadeModel(GL_SMOOTH);
        glPushMatrix();
        glRotatef(cspin, 0.0, 0.0, 1.0);
        cspin ++;
        glColor3f(1.0, 1.0, 0.0);
        glutSolidCube(5.0);
        glutSolidTorus(1.0, 2.0, 2.0, 20);
        glDisable(GL_LIGHTING);
        glPopMatrix();
}*/

bool intersectWalls()
{
        for(CSLIST::iterator i = walls.set.begin(); i != walls.set.end(); ++i)
        {
                if (intersectWall(*i)) return true;
        }
        return false;
}

void display()
{
        glClear(GL_COLOR_BUFFER_BIT);
        glClear(GL_DEPTH_BUFFER_BIT);
       
        glMatrixMode(GL_PROJECTION);
        //glLoadIdentity();
        glPushMatrix();
        //glTranslatef(x, y, z);
        //glTranslatef(-x, -y, -z);
        glRotatef(xspin, 1.0, 0.0, 0.0);
        glRotatef(yspin, 0.0, 1.0, 0.0);
        glRotatef(zspin, 0.0, 0.0, 1.0);
        glTranslatef(-x, -y, -z);
        //glTranslatef(-x, -y, -z);
        /*glRotatef(xspin, 1.0, 0.0, 0.0);
        glRotatef(yspin, 0.0, 1.0, 0.0);
        glRotatef(zspin, 0.0, 0.0, 1.0);*/
        //gluPerspective(30.0, 4.0 / 3.0 , 0.5, MSIZE + 1);
        //glTranslatef(0, 0, -1.5);
        //glRotatef(cspin, 0.0, 1.0, 0.0);
        glColor4f(1.0, 1.0, 1.0, 0.0);
        //cspin += 0.5;
               
       
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glTranslatef(x, y, z); // - 1.5);
        glRotatef(-xspin, 1.0, 0.0, 0.0);
        glRotatef(-yspin, 0.0, 1.0, 0.0);
        glRotatef(-zspin, 0.0, 0.0, 1.0);
        glTranslatef(0, 0, -1.5);
        //glRotatef(xspin, 0.0, 1.0, 0.0);
        //glRotatef(cspin, 0.0, -4.0, 0.0);
        //glRotatef(cspin, 0.0, 0.0, -4.0);
       
        glutSolidTeapot(0.1);

        glPopMatrix();
       
        //Character player(cx, cy, cz);
        //player.draw();
       
        CSLIST::iterator i;
       
        for(i = walls.set.begin(); i != walls.set.end(); ++i)
        {
                drawWall((*i));
        }
       
        //glPopMatrix();
        glMatrixMode(GL_PROJECTION);

        glPopMatrix();
       
        //glMatrixMode(GL_MODELVIEW);
       
        glFlush();
       
        glutPostRedisplay();
}
void keyboard() {
        if (GetAsyncKeyState(0x57) & 0x8000)
        {
                y += 0.01;
                if(intersectWalls()) y -= 0.01;
                else cout << y << endl;
                //cout << z << endl;
                //yspin = 90;
                //xspin = 0;
                //yspin = 0;
                //zspin = 0;
        }
        if (GetAsyncKeyState(0x41) & 0x8000)
        {
                x -= 0.01;
                if(intersectWalls()) x += 0.01;
                //yspin = 270;
                //xspin = 0;
                //xspin = 0;
                //yspin = 0;
                //zspin = 0;
        }
        if (GetAsyncKeyState(0x44) & 0x8000)
        {
                x += 0.01;
                if(intersectWalls()) x -= 0.01;
                //xspin = 0;
                //yspin = 0;
                //zspin = 0;
        }
        if (GetAsyncKeyState(0x53) & 0x8000)
        {
                y-= 0.01;
                if(intersectWalls()) y += 0.01;
                //cout << z << endl;
                //xspin = 0;
                //yspin = 0;
                //zspin = 0;
               
        }
        if (GetAsyncKeyState(0x20) & 0x8000)
        {
                tx = cx;
                ty = cy;
                tz = cz + 20;
        }
        if (GetAsyncKeyState(0x26) & 0x8000)
        {
                z -= 0.01;
                //xspin = 180; //++;//; = 180;
                //yspin = 0;
                //zspin = 180;
                //zspin = 180;
                if(intersectWalls()) z += 0.01;
                //xspin = 180;

        }
        if (GetAsyncKeyState(0x28) & 0x8000)
        {
                z += 0.01;
                if(intersectWalls()) z -= 0.01;
                //xspin = 0;
                //yspin = 0;
                //zspin = 0;
        }
}

void init() {
        glEnable(GL_DEPTH_TEST);
        //glEnable(GL_BLEND);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        //glOrtho(-0.5, 0.5, -0.5, 0.5, -5, 5);
        gluPerspective(30.0, 4.0 / 3.0 , 0.5, MSIZE + 1);
        glMatrixMode(GL_MODELVIEW);
        //glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0);
        glLoadIdentity();
        //makedense(-500.0, -500.0, -500.0, 1000.0, 1000.0, 1000.0,
        //              -500.0, -500.0, -500.0, 1000.0, 1000.0, 1000.0);

        glEnable(GL_FOG);
        {
                GLint fogMode;
                GLfloat fogColor[4] = {0.0, 0.0, 0.0, 1.0};

                fogMode = GL_EXP;
                glFogi(GL_FOG_MODE, fogMode);
                glFogfv(GL_FOG_COLOR, fogColor);
                glFogf(GL_FOG_DENSITY, 0.5);
                glHint(GL_FOG_HINT, GL_DONT_CARE);
                glFogf(GL_FOG_START, 1.0);
                glFogf(GL_FOG_END, 10.0);
        }
        glClearColor(0.0, 0.0, 0.0, 1.0);
}

/*int main(int argc, char **argv)
{
        //srand(time(NULL));
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
        glutInitWindowSize(800, 600);
        glutInitWindowPosition(100, 100);
        glutCreateWindow("Paul is so awesome you are freaking out");
        init();
        glutDisplayFunc(display);
        glutIdleFunc(keyboard);
        //glutMouseFunc(mouse);
        glutMainLoop();
        return 0;
}*/

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

        CSSet conn;

        srand(time(NULL));
       
        for(int x=0;x<MSIZE;x++)
        {
                for(int y=0;y<MSIZE;++y)
                {
                        for(int z=0;z<MSIZE;++z)
                        {
                                Cell cell;
                                cell.x = x;
                                cell.y = y;
                                cell.z = z;
                                if (cell.x == 0){
                                        CellSet edge;
                                        Cell cell2 = cell;
                                        cell2.x = -1;
                                        edge.merge(CellSet(cell));
                                        edge.merge(CellSet(cell2));
                                        walls.merge(CSSet(edge));
                                }
                                else if (cell.x == MSIZE-1){
                                        CellSet edge;
                                        Cell cell2 = cell;
                                        cell2.x = MSIZE;
                                        edge.merge(CellSet(cell));
                                        edge.merge(CellSet(cell2));
                                        walls.merge(CSSet(edge));
                                }
                                if (cell.y == 0){
                                        CellSet edge;
                                        Cell cell2 = cell;
                                        cell2.y = -1;
                                        edge.merge(CellSet(cell));
                                        edge.merge(CellSet(cell2));
                                        walls.merge(CSSet(edge));
                                }
                                else if (cell.y == MSIZE-1){
                                        CellSet edge;
                                        Cell cell2 = cell;
                                        cell2.y = MSIZE;
                                        edge.merge(CellSet(cell));
                                        edge.merge(CellSet(cell2));
                                        walls.merge(CSSet(edge));
                                }
                                if (cell.z == 0){
                                        CellSet edge;
                                        Cell cell2 = cell;
                                        cell2.z = -1;
                                        edge.merge(CellSet(cell));
                                        edge.merge(CellSet(cell2));
                                        walls.merge(CSSet(edge));
                                }
                                else if (cell.z == MSIZE-1){
                                        CellSet edge;
                                        Cell cell2 = cell;
                                        cell2.z = MSIZE;
                                        edge.merge(CellSet(cell));
                                        edge.merge(CellSet(cell2));
                                        walls.merge(CSSet(edge));
                                }
                                //if (cell.x)
                                maze.merge(CellSet(cell));
                                CellSet initial(cell);
                                conn.merge(CSSet(initial));
                        }
                }
        }
       
        for(CLIST::iterator i = maze.set.begin();i!=maze.set.end(); ++i)
        {
                for(CLIST::iterator j =maze.set.begin(); j!=maze.set.end(); ++j)
                {
                        if((*i).adjacent(*j)) {
                                CellSet edge;
                                edge.merge(CellSet(*i));
                                edge.merge(CellSet(*j));
                                walls.merge(CSSet(edge));
                        }
                }
        }

        while(conn.set.size()>1)
        {
                int _size = conn.set.size();
                int i = rand()%walls.set.size();
                CSSet wallset;
                CSLIST::iterator wall = walls.get(i);
                CSLIST::iterator cset = conn.set.begin();

                while(cset!=conn.set.end()) {
                        for (CLIST::iterator j=(*wall).set.begin(); j !=(*wall).set.end(); ++j)
                        {
                                if( (*cset).member(*j)) {
                                        wallset.merge(CSSet(*cset));
                                }
                        }
                        ++cset;
                }
                if (wallset.set.size() > 1) {
                        conn.difference(wallset);
                        CellSet merged;
                        for (CSLIST::iterator j=wallset.set.begin(); j != wallset.set.end(); ++j)
                        {
                                merged.merge(*j);
                        }
                        conn.merge(CSSet(merged));
               
                        walls.difference(CSSet(*wall));
                }
                if (conn.set.size() != _size) { cout << conn.set.size() << endl;}
       
        }

        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
        glutInitWindowSize(800, 600);
        glutInitWindowPosition(100, 100);
        glutCreateWindow("Paul is so awesome you are freaking out");
        init();
        glutDisplayFunc(display);
        glutIdleFunc(keyboard);
        //glutMouseFunc(mouse);
        glutMainLoop();
        return 0;
}

video/image editing

by therstonsplace at 16:17 PM, 09/02/2010

so im writing some video/image editing software and im stumped... not about the code so much cuz what im doing works fine .. im not convinced it is the most efficient use of my computer but it works.

first my code...
 #include <iostream>
#include <fstream>

using namespace std;
                       
int main()
{
    fstream obj ("sample.jpg", ios::in | ios::binary);
    fstream obj2("sample2.jpg, ios::out | ios::binary);
    int x, length;
    obj.seekg(0, ios::end);
    length = obj.tellg();
    char array[length];

      obj.seekg(0, ios::beg);
      while(!obj.eof())
      {

          array[x] = obj.get();
          obj2.put(array[x]);         
          x++;

      };

    obj.close();
    obj2.close();
}



okay so my question is im not sure how jpg's or .mov's any image or movie extension is packed a way... i realize that it is a combination of 3 bytes.... so for black 3 characters would all have ffffff..


my question is where do i go to learn how these bits are packed away so i can manipulate them... any standard that would be published... (preferrably something simple but unlikely)

thank you

C++ headers

by myk45 at 12:51 PM, 09/02/2010

Hello.

Well, unlike C, C++ provides a concept of headers(not header files) and that these headers are something like a collection of names, which may mapped as header files by the compiler.

Can anyone please correct me if im wrong in my above understanding. Also please state the main difference between a namepace and a header.(since even a C++ header is a collection of names)

Thanks in advance.

create a simple programming language

by Redhaze46 at 11:34 AM, 09/02/2010

Hello all..

is it possible to create my own simple programming language in c++?
complete with the compiler,editor and the libraries..
just a basic model where i can write simple instructions,save it with my own extension
and run atleast a few simple algorithms..

Using variable length variable (bitset)

by myk45 at 11:05 AM, 09/02/2010

Hello.

i needed a variable size bit string. And since bitset provides several operations, i wanted to use it. But is it possible to make it a variable size one?

class TryBits {
  private:
          string s;
          bitset<n> b; //now i need n = s.size().
};

How can i achieve this?
Thanks

characters should appear on mouse focus :(

by localp at 10:00 AM, 09/02/2010

I need to write a C++ code, where if theres a String called "hello" in the code each character should appear (character by character) on the mouse focus.

That means where ever i click my mouse (Even on an external program), and when the on focus sign appears the characters of "hello" should appear there.

I studies that theres a function in C++ called SendKeys but i am not sure if its that i should look for. Can some one tell me the keywords to google or if your'l know any example to start on, please tell me, because it would be very useful.

Help !!

Sensing The Caps Lock Key

by walter clark at 08:42 AM, 09/02/2010

I'd like to know what the ASCII codes for the toggle keys of the keyboard. I want to make the mouse clicks do different thing when the Caps Lock, or Scroll Lock is pressed.

Walt

Template arguments

by onako at 07:15 AM, 09/02/2010

My templated function look as follows:
template <typename MatTypeOne, typename MatTypeTwo>
void funct(MatTypeOne& m1, MatTypeTwo& m2) {
    //here I would need to check whether m1 and m2 are of the same "type",
    //meaning that MatTypeOne is the same as MatTypeTwo
}
What is the way to check whether m1 and m2 belong to same/different types?
Thanks

Custom Title Bar

by PixelExchange at 07:11 AM, 09/02/2010

I realize that there are plenty of tutorials on how to create a "Custom Win32 Title Bar." The problem is.. none of the tutorials I have found so far.. discusses how a person would be able to "drag" the replaced title bar.. as one would drag the "normal" title bar.

If you do not know what I mean by "custom" title bar.. it only means that I would like to remove the "initial" window title bar (..the bar upon which the window's title resides) and replace it with one that I drew myself. Not only would I like to replace the standard title bar however.. but I would like to learn how to be able to drag the window from MY custom title bar image.. as one would drag the screen with the standard title bar.

Also.. if it is possible.. I would like to replicate the functionality which the WS_THICKFRAME attribute provides to a window.. only on custom bitmaps.

Example: I want a user to be able to click on lines that I drew.... which would reuslt in the window being scaled.. (as would occur if a person scaled a window with the default window sides provided).

final project, last error

by cnmsg007 at 06:58 AM, 09/02/2010

The only error stated is at "N_showdata.N_enterData();" which says "error C2660: 'NomineeData::N_enterData' : function does not take 0 arguments"
#include<iostream>
#include<conio.h>
#include<string> 
using namespace std;

class MemberData
{       
private:       
        int ID ;       
        char Name[60];       
        char Add[60];       
        char Tel[15];       
public:       
        void enterData();       
        void showData(void);
};
void MemberData::enterData()
{       
        cout << "Please enter your Membership number: " << endl;       
        cin >>ID;       
    cout << "Please enter your Name: "<< endl;       
        cin >>Name;       
    cout << "Please enter your Address: " << endl;       
        cin >>Add;       
    cout << "Please enter your Handphone number: " << endl;       
        cin >>Tel;
}
void MemberData::showData(void)
{       
        cout << "Member ID is: "<< ID << endl;
        cout << "Member Name is: "<< Name << endl;
        cout << "Member's Add is: "<< Add << endl;
        cout << "Member's Tel is: "<< Tel << endl;
}
class  NomineeData : public MemberData  //Derived from class MemberData allow the user enter
                                          //the nominees' particular
{
private:
        char N_ID[20];
        char N_Name[20];
public:
        void N_enterData(char N_ID, char N_Name);
        void N_showData(void);
};
void NomineeData::N_enterData(char N_ID, char N_Name)
{
        cout << "Please enter Nominee's ID: " << endl;
        cin >> N_ID;
        cout << "Please enter Nominee's Name: " << endl;
        cin >> N_Name;
}
void NomineeData::N_showData(void)
{
        cout << "Nominee's ID is: "<< N_ID << endl;
        cout << "Nominee's Name is: "<< N_Name << endl;
}
class ShowNname : public NomineeData  //Derived from class MemberData
{
private:
        string JamesTan, BennyKoh, StevenLim, DavidTay, MaryTan;
public:
        void Showname();
};
void ShowNname::Showname(void)
{
        cout << "Nominee No.1 "<<"  JamesTan"<<endl;
        cout << "Nominee No.2 "<<"  BennyKoh"<<endl;
    cout << "Nominee No.3 "<<"  StevenLim"<<endl;
        cout << "Nominee No.4 "<<"  DavidTay"<<endl;
        cout << "Nominee No.5 "<<"  MaryTan"<<endl;
}
int main()
{
        MemberData show_data;
        NomineeData N_showdata;
        ShowNname show_name;

        show_data.enterData();       
        show_data.showData();
        N_showdata.N_enterData();
        N_showdata.N_showData();
        show_name.Showname();

       
    int Vote_Amount[6]={0};//set amunt of votes
    int key=0;
        cout << "Please vote nominee by enter the noimee number" << endl;

        while((key=getch())!=0x27)
        {
                switch(key)
                {
                        case '1':Vote_Amount[1]++;break;
            case '2':Vote_Amount[2]++;break;
            case '3':Vote_Amount[3]++;break;
            case '4':Vote_Amount[4]++;break;
            case '5':Vote_Amount[5]++;break;
                }

                for(int i=1;i<6;i++)
                        cout<< "Nominee No."<< i <<" won "<<Vote_Amount[i]<< " vote(s)"<<endl;
        }
        return 0;
}

use c++ compiler

by Redhaze46 at 06:39 AM, 09/02/2010

hello all..,

can i use c++ libraries and the compiler to create my own interface?
i just want to use a different gui for it..
a new editor of sorts.if yes then how do i go by it?
thanks..

Why doesn't this cause a SIGABRT signal

by Sinaru at 05:48 AM, 09/02/2010

Take a look at this program.
#include <iostream>
using namespace std;

struct Node
{
    int data;
    Node* link;

    Node()
    {
        data = 0;
        link = NULL;
    }
};

void destroy(Node* &p)
{
    Node* pre;

    while(p !=NULL)
    {
        pre = p;
        p = p->link;
        delete pre;  // When running for the second time, pre value becomes
                      // 0x602030 but when the statement executes , it doesn't
                      // cause a SIGABRT
    }
}

int main()
{
    Node* ints;
    ints = new Node; // link a node

    ints->link = new Node; // link another node

    delete ints->link; // Delete the second node (value: 0x602030)
    // If I run the above statement again in main, it will casue a SIGABRT
    //signal with the following message. media/<My project location>/dist/
    //debug/ cppapp: double free or corruption (fasttop): 0x0000000000602030 ***

    destroy(ints);
    return 0;
}

I'm using debug mode and if I run "delete ints->link" statement twice in main, gdb will say the program cause a SIGABRT, when it hits the second delete statement because I free the same memory twice. But this doesn't happen when I run destroy method like in the above code.

In other words, According to my knowledge I'm freeing the same memory twice in the above program. It should cause a SIGABRT signal, right? but it doesn't. I need to know whether it's my mistake(ie. understanding in a wrong way or code error) or something wrong with the compiler?

I'm using g++ 4.4.3, Netbeans IDE, Ubuntu 10.4, gdb. I used gdb to see where the pointers point.

string::npos = -1?

by maceron at 05:40 AM, 09/02/2010

Just a quick question, if string::npos represents the largest possible value for a string object, how can this value be -1 if it's an unsigned integer?
I know this value will change for different compilers, as string::npos on my compiler is set to 4,294,967,295 which makes sense but I don't understand how -1 can represent the largest value.

Thanks in advance

writing into binary file

by dineshcbe at 05:07 AM, 09/02/2010

I have a problem when i am writing a content into a files as a binary format.I noticed, that it writes the content two times into the file.
Here is the code.


#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class store
{
protected:
char pass[50];
public:
fstream file;
store();
~store();
void writing();
void reading();
};
store::store()
{
file.open("binary.dat",ios::in | ios::out | ios::app | ios::binary);
}
store::~store();
{
file.close();
}
int main()
{
store b;
b.writing();
b.reading();
return 0;
}
void store::writing()
{
char buf[] = "hello";
strcpy_s(pass,sizeof(buf),buf);
file.write(reinterpret_cast<char*>(&pass),sizeof(pass));
}
void store::reading()
{
file.seekp(0,ios_base::beg);
while(!file.eof())
{
file.read(reinterpret_cast<char*>(&pass),sizeof(pass));
cout<<pass;
}
}
I have a design question which I have not been able to find a satisfactory answer for by searching.

Essentially, I have a class - Base - that contains a vector of pointers to another class - Node. However, I would like to be able extend both the Base and Node class. This will involve adding new variables and functions to the classes derived from Node, and utilising these additional functions in classes derived from Base.

I can think of a few ways to accomplish this, but am unsure which is the best from a design point of view, as they each have their flaws. It has led me to think that perhaps there is a different design altogether which can accomplish what I need more elegantly.

Here is some example code illustrating my problem:
class Node
{
protected:

int value;

public:

Node(int v): value(v)
        { }
void GetValue()
        { return value; }
virtual void Print()
        {
        std::cout << "Value is: " << value << std::endl;
        }
};


class BetterNode: public Node
{
protected:

double another_value;

public:

BetterNode(int v, double v2): Node(v), another_value(v2)
        { }
void GetBetterValue()
        { return another_value; }
virtual void Print()
        {
        Node::Print();
        std::cout << "Better Value is: " << another_value << std::endl;
        }
};


class Base
{
protected:

std::vector< Node* > some_nodes;

virtual void MakeNodes()
        {
        for(int i = 0; i < 10; i++)
                some_nodes.push_back( new Node(i) );
        }

public:

Base()
        {
        Initialise();
        }
void PrintNodes()
        {
        for(int i = 0; i < some_nodes.size(); i++)
                {
                std::cout << "Node " << i << ":" << std::endl;
                some_nodes[i]->Print();
                }
        }

int AddValues()
        {
        int temp = 0;
        for(int i = 0; i < some_nodes.size(); i++)
                temp += some_nodes[i]->GetValue();
        return temp;
        }
       

};


class BetterBase
{

virtual void MakeNodes()
        {
        for(int i = 0; i < 10; i++)
                some_nodes.push_back( new BetterNode(i, i/2) );
        }

public:

BetterBase()
        {
        Initialise();
        }

double AddBetterValues()
        {
        double temp = 0;
        for(int i = 0; i < some_nodes.size(); i++)
                temp += some_nodes[i]->GetBetterValue(); // THE PROBLEM LIES HERE.
        return temp;
        }

};


int main(void)
{

Base * b = new Base;
Base * better_b = new BetterBase;

// Output details about Nodes:
b->PrintNodes();
// Virtual function in BetterNode takes over and outputs additional Detail:
better_b->PrintNodes();

// Lets find out what the sum of the node values from b are:
int b_values = b->AddValues();
std::cout << b_values << std::endl;

// We *know* that better_b contains additional information. What is it?
double better_values = better_b->AddBetterValues();
std::cout << better_values << std::endl;
// But ofcourse, this compiles with an error, because AddBetterValues does not exist in Base class..

return 0;
}


So, My derived BetterNode class is naturally going to extend the base Node class, and will need new values and consequently new functions to access them, that are unknown to the base Node class. However, it will share the common base properties.

In addition, the derived BetterBase class wishes to implement these BetterNodes and utilise their additional functionality in performing what it does. It will fill its some_nodes vector with pointers to BetterNodes. It can therefore use all of its parent Base class functions, as the BetterNode is derived from the Node.

I have tried to illustrate this problem in the above code. I do not need to reimplement my Print function, as classes derived from Node can virtually overload the Print function, which saves me effort. This is good. However, My derived BetterBase class wants to make use of the extended functionality of BetterNode, in this example by implementing AddBetterValues(). It obviously cannot, as the vector some_nodes is pointers to the base Node class, which does not know about this function.

So, How can I pull this off?

I have thought of a few ways, but am unsure which is best:

1. Make the Base class a template class, whereby I select which type of Node the vector some_nodes will hold.
example:

template<class T = Node> Base
{
protected:

vector<T*> some_nodes;

//...other code.
};

class BetterBase: public Base<BetterNode>
{
// now, AddBetterValues would work, as the vector is not of base class Node, but of BetterNode.
}

The problem here is that it allows for mistakes to be made. What if I derive from the Base class like this:

class AnotherBase: public Base<NonNodeClass>

Templating allows me to fill that vector with anything, not just classes derived from Node, which could screw things up. As such, this seems like a sloppy and potentially error-prone workaround.

2. Whenever I add functions to classes derived from Node, I can also prototype/define these functions as virtual in the base Node class. Now, the base class knows about additional functions, and there are no issues,

However, this seems like bad design practise, and people who derive from my classes should not need to go back and add relevant code into my base Node class. In addition, bulking out the base Node class with functions it does not itself need is just stupid.

3. Casting in derived classes. If, knowing that I will be using BetterNodes in the BetterBase class, I simply cast from Node* to BetterNode* when necessary, I would provide the additional BetterBase functions access to the required additional BetterNode functions. The downside to this approach is the requirement for an increasing amount of casting as the class derived from Node grows more complex, which seems sloppy. Also, people tend to say that this is a sign of a design flaw. As it seems like the simplest way to overcome my problem, does this mean that there is a better way I could structure my code?


So, which method is best? Or, do I need to think about redesigning my code entirely?

Thanks in advance for your help!
James,
How we can randomly generate and store the age of N employees in Arrays plssssss

How to deal the Card ???

by myd5258 at 02:17 AM, 09/02/2010

Can some1 giv me some clues to cont the deal card to players part ??? The program will deal cards once the user enter the numbers of player between 3-7, either five cards per player or seven cards per player depending upon the menu selection, to the players at the table. The dealer, the program, always is dealt to last.


#include <iostream>
#include <string> // string
#include <ctime>
#include <iomanip>
#include <cstdlib>
using namespace std;

struct card{
      char suit ;
      char rank ;
      }deck[52];
     


void GenerateRandom (card *ptrCard, int arraySize);
void Display (card *ptrCard, int arraySize);
void dealCard (card *ptrCard, int pNum, int cardSize);


const char *wSuit [] = {"Spades", "Hearts", "Clubs", "Diamonds"};
const char *wRank []= {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};



int main ()
{

  card deck[52];
  card *ptrCard = new card [52];
 
    int num , playerNum, numSelect ;
    srand (time (NULL));
     
 
    do{
    cout<<"1. Deal Five Cards"<<endl;
    cout<<"2. Deal Seven Cards"<<endl;
    cout<<"3. Quit the Game"<<endl;
    cout<<endl;
    cout<<"Enter Selection : "<<flush;
    cin>>numSelect;
    cout<<endl;
   
    switch (numSelect){
          case 1 : cout<<"You chosed deal five cards."<<endl;
                    cout << "\n\nGenerate Random Cards :\n\n";
                    num = 5;
                   
                    break;
          case 2 : cout<<"You Chosed deal seven cards."<<endl;
                    cout << "\n\nGenerate Random Cards :\n\n";
                    num = 7;
                   
                    break;
          case 3 : exit (1);
                    break;
          default: cout<<"  Wrong Selection. Please choose again !!! "<<endl;
                    cout<<endl;
          }
      }while (numSelect > 3 || numSelect <= 0);
   
   
   
 
 
    GenerateRandom (ptrCard, 52);
       
    Display (ptrCard, 52);
    dealCard (ptrCard, playerNum, num); 
     
     
    delete [] ptrCard; // delete card array   
    system("pause");
    return 0;
   
}
   
   
void GenerateRandom (card *ptrCard, int arraySize){
 
// this method will generate repeated random numbers.  boolean array
// keeps track of what numbers have been picked.  Generates another if
// this number has already been picked.

 
    bool* picked =  new bool[52];
    // initialize 52 cards to unpicked
    for (int i = 0; i < 52; i++)
        picked[i] = false;
       
    int value;
    //assumes all the generated cards are different in location for every new game
    for (int i = 0; i < arraySize; i++)
    {
        value = rand () % 52; 
        if (!picked[value])
        {
            ptrCard[i].rank = value;
            ptrCard[i].suit = value;      // card hasn't been picked then  assign into array,
            picked[value] = true;        // flag as picked.
            }
        else
            i--;  // already picked.
      }

    delete [] picked;
}

void Display (card *ptrCard, int arraySize)
{
    for (int i = 0; i < arraySize; i++)
    {
          cout <<right << setw( 3 ) <<i + 1<< ". "<< right << setw( 5 ) << wRank[ptrCard[i].rank % 13] << " of "
              << left << setw( 8 ) <<wSuit[ptrCard[i].suit % 4]<< (  (i + 1) % 2 ? '\t' : '\n' ) ;
       
    }
}

void dealCard (card *ptrCard, int pNum, int cardSize)
{
    do{
    cout<<"Enter the players Number: "<<flush;
    cin>>pNum;
    }while (pNum < 3 || pNum > 7);
   
    int cardRange = pNum * cardSize;
    int *player = new int[pNum];
   
  /****************
    for (i=0; i<pNum ; i++)
    {                            ***HOW TO PASS GENERATED RANDOM CARDS TO THE PLAYERS ???
                               
        player[i]
        } ************/
   
    for (int i=0 ; i < cardRange; i++)
    {
       
        cout <<right << setw( 3 ) <<i + 1<< ". "<< right << setw( 5 ) << wRank[ptrCard[i].rank % 13] << " of "
              << left << setw( 8 ) <<wSuit[ptrCard[i].suit % 4]<< (  (i + 1) % cardSize ? '\t' : '\n' ) ;
       
       
        }
       
   
   
    cout<<endl;
   
    delete [] player;
 
}

Win32 Window Creation Problem

by PixelExchange at 02:16 AM, 09/02/2010

Hi everyone.

I already know how to create a program using just one window.. but I'm having trouble creating a program with 2 windows.

I used CreateWindow() to create my second window, however, my second window displays exactly what is on my main window!

I figured the reason was because my WinProc function was handling messages for all windows (including the second window), and so on WM_PAINT, everything intended to be painted on the main window.. also gets displayed on the second window as well.

What I would like to know is how I would get my second window to have its window messages handled by a SEPERATE handling function (aside from WinProc).

Note: I've already managed to create a second WndProc function, the problem is.. I do not know how to set my second window.. to USE that second WndProc function. Even though there is a second WndProc function created.. my second window still utilizes the first WndProc function for all of its window messages!

Thank you for your help.

urgent!! help me find out the errors pls!! thanks!

by cnmsg007 at 01:09 AM, 09/02/2010

#include<iostream>
#include<string>
#define MAXnominees 3
using namespace std;

class MemberData
{
protected:
    int    ID ;
    char    Name[20];
    char    Add[20] ;
    char    Tel[15] ;
public:
        void enterData();
        void showData(void);
};

void MemberData::enterData() //allow user enter member's particular
{
        cout << "Please enter your Membership number: " << endl;
        cin >>ID;
        cout << "Please enter your Name: "<< endl;
        cin >>Name;
        cout << "Please enter your Address: " << endl;
        cin >>Add;
        cout << "Please enter your Handphone number: " << endl;
        cin >>Tel;
}
void MemberData::showData(void) //show member's particular
{
        cout << "Member ID is: "<< ID<<endl;
        cout << "Member Name is: "<<Name<<endl;
        cout << "Member's Add is: "<<Add<<endl;
        cout << "Member's Tel is: "<<Tel<<endl;
}
class  NomineeData : public MemberData  //Derived from class MemberData allow the user enter
                                          //the nominees' particular
{
private:
        int N_ID[20];
        char N_Name[20];
public:
        void N_enterData(int, char);
        void N_showData(int, char);
};
void NomineeData::N_enterData(int N_ID, char N_Name)
{
        cout << "Please enter Nominee's ID: "<< endl;
        cin >> N_ID;
        cout << "Please enter Nominee's Name: "<< endl;
        cin >> N_Name;
}
void NomineeData::N_showData(int, char)
{
        cout << "Nominee's ID is: "<< N_ID << endl;
        cout << "Nominee's Name is: "<< N_Name << endl;
}
class Set_Nnum : public NomineeData  //Derived from class MemberData to assign no to nominees
{
private:
        char "James Tan", "Benny Koh", "Steven Lim", "David Tay", "Mary Tan";
public:
        void Setname(void);
};
void Set_Nnum::Setname(void)
{
        "James Tan" = 1;
        "Benny Koh" = 2;
        "Steven Lim" = 3;
        "David Tay" = 4;
        "Mary Tan" = 5;
}
int main()
{
        MemberData showdata;
        NomineeData N_showdata;

        showdata.enterData;
    showdata.showData();
        N_showdata.N_enterData();
        N_showdata.N_showData();
}

Help in OOP

by medopunsher at 19:02 PM, 09/01/2010

Hello Everyone ,
I'am new to OOP and QT and i'm trying to write a simple chat program (client , server) with winsockets.
I Have an error which i don't seem to understand :

this is my code so far :

#include "pmessenger.h"
#include "ui_pmessenger.h"
#include <QMessageBox>
#include <winsock2.h>
SOCKET s;
PMessenger::PMessenger(QWidget *parent) : QMainWindow(parent), ui(new Ui::PMessenger)
{
    ui->setupUi(this);
    WSADATA wsadata;
    if(WSAStartup(MAKEWORD(2,2),&wsadata)!=0)
    {
        QMessageBox::critical(this,"Error","Winsock Startup Failed",0,0);
        this->close();
    }
    s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(s==INVALID_SOCKET)
    {
          QMessageBox::critical(this,"Error","Socket Creation Faild",0,0);
          WSACleanup();
          this->close();
    }
    SOCKADDR_IN server;
    server.sin_family = AF_INET;
    server.sin_port = htons(7676);
    server.sin_addr.s_addr = inet_addr("my ip is here :D");
    if(::connect(s,(sockaddr*)&server,sizeof(server))!=0)
    {
          QMessageBox::critical(this,"Error","Can't Connect",0,0);
          WSACleanup();
          this->close();
    }
    CreateThread(NULL,0,ServerMsgThread,(LPVOID)s,0,0); // the problem is in this line :(
}

PMessenger::~PMessenger()
{
    delete ui;
}

void PMessenger::on_pushButton_clicked()
{
    QString msg = ui->plainTextEdit_2->toPlainText();
    send(s,(const char *)msg.data(),4096,0);
}

void PMessenger::AddMessege(char msg[4096])
{
    ui->plainTextEdit->appendPlainText(msg);
}

DWORD PMessenger::ServerMsgThread(LPVOID pParam)
{
      SOCKET Cs = (SOCKET) pParam;
      char data[4096];
      while(1)
      {
          if(recv(Cs,data,1024,0)>0)
              AddMessege(data);
      }
      return 0;
}

I Get the following error :

..\PMessenger\pmessenger.cpp:32: error: argument of type 'DWORD (PMessenger:: )(void*)' does not match 'DWORD (*)(void*)'

Any help would be greatly appreciated (i really don't want to move to wxWidgets because of that error)

Thanks

Reversing an array of chars (algorithm for this?)

by bmos31 at 17:11 PM, 09/01/2010

Ok, so I'm writing a program to convert decimal into binary. It all works with the exception that my binary shows up in reverse order and I'm having trouble with reversing the array of chars in my intToBinaryString() function.

Any tips on how to get this started?

#include<iostream>
#include<cstring>

using namespace std;

void intToBinaryString(long int, char []);

#define ARRAY_SIZE 10001

int main()
{
    long int number;
    char binary[ARRAY_SIZE];
    int count = 0;

    cout << "Enter a non-negative integer to convert to binary: ";
    cin >> number;
    if(number >= 0)
    {
        cout << "The binary representation for " << number << " is: ";
        intToBinaryString(number, binary);
    }
    else
    cout << "Enter a non-negative number" << endl;
    cout << endl << endl;
   
    system ("pause");
    return 0;
}

void intToBinaryString(long int num, char bin[])    //NOTE:check pg 817 for c-string info
{
    int remainder, n=0;
    char tempArray[ARRAY_SIZE];
   
    do
    {
        remainder = num%2;
        num = num/2;
        itoa(remainder, tempArray, 10);
        cout << tempArray;         
    }while(num > 0);                     
}

arrayas part2

by exekiel101 at 13:59 PM, 09/01/2010

 #include <iostream>
#include <iomanip>
 using namespace std;
 int main() {


 
      int rows;
      cout<< "put the number of rows here"" ";
          cin >> rows;
    cout<< "numbers here""\n ";
          int *arr = new int[ rows ];
          for( int i = 0; i < rows; i++ ){

                  cin >> arr[ i ];
       
          } 
      cout endl; 
      int col;
    cout<< "put the number of columns here"" ";
      cin >> col;
      cout<< "numbers here""\n ";
          int *arra = new int[ col ];
          for( int j = 0;j < col; j++ ){
     
                  cin >> arra[ j ]; 
       
          }
 
       
          return 0;
                }

i want to have a multiplication table after this commands...how can i?? ove try it all

Creating rows of asterisks???

by wakesin at 13:00 PM, 09/01/2010

hey there Daniweb.

So I am in need of some help with a project I have.

We need to create a program that will print out rows of asterisks as tall as defined by the user.
For example, if the user entered, 1 2 3 4 3 2 1 10 0, my program should print:

      *
      *
      *
      *
      *
      *
  *  *
  ***  *
 ***** *
********
1 star in the first row, 2 in the 2nd, and so on.

so far all i have is that i need to place the numbers in an array.....I am very lost and any insight would be appreciated!

array

by exekiel101 at 12:46 PM, 09/01/2010

i cannot get the logic of this thing...

i will input the number of rows

example "rows=5"

then

"input the numbers = 2 3 8 9 7"

what codes could i use???

Copying from std::vector to memory buffer

by tron_thomas at 12:37 PM, 09/01/2010

I have a situation whereby I need to copy the contents of an STL vector into a memory buffer provided by the system. One might think that given:

std::vector<ObjectType> source; // Initalized to hold the objects
ObjectType* target = reinterpret_cast<ObjectType*>(buffer); // Points to system provided memory buffer

someone could do the following:

std::copy(source.begin(), source.end(), target);

This can be problematic, however, because ObjectType is a complex class whose instances contain instances of other classes. The memory buffer from the system is raw memory which does not have properly constructed objects in it, so the copy algorithm would be performing an assignment to an improperly constructed ObjectTypes.

One way to work around this would be something like the following:

const size_t COUNT = source.size();

for(size_t index = 0; COUNT > index; ++index, ++target){
    new(target) ObjectType(source[index]);
}

This technique uses placement new and the copy constructor to create copies of the items from the vector into the memory buffer. This will work as ObjectType does have a valid, public copy constructor.

I'm wondering if a more elegant solution can be developed that can still allow the use of the std::copy algorithm to accomplish this task. Perhaps someone could use an object similar to std::inserter and can be used on an array, like maybe some sort of replacer object that does the job of the placement new operator in the above loop when called in something like the copy algorithm.

I'm wondering if such an object already exists, that someone can make use of. If something doesn't exist, I'm wondering how practical it would be to create such a thing.

Also, perhaps there is another way to solve the problem that doesn't involve anything suggested so far.

What do people suggest for solving this problem?

3 q's about inheritance, pointers, polymorphsm

by fizzix66 at 12:14 PM, 09/01/2010

see comments. set me straight. many, many thanks...

3 questions about inheritance, pointers, & polymorphism

#include <iostream>
using namespace std;

class baseClass {
  public:
    void nVirt() {
        cout << "not virtual, base " << endl;
    }
    virtual void yVirt() {
        cout << "virtual, base " << endl;
    }
};

class derivedClass : public baseClass {
  public:
    void nVirt() {
        cout << "not virtual, derived " << endl;
    }
    virtual void yVirt() {
        cout << "virtual, derived " << endl;
    }
};

int main()
{
    baseClass someBase;        //base obj
    baseClass * basePtr;        //base obj pointer
    derivedClass someDerived;  //derived obj
    derivedClass * derivedPtr;  //derived obj pointer

    basePtr = &someBase;        //set base obj pointer to base obj
    basePtr->nVirt();          //as expected
    basePtr->yVirt();          //as expected

    basePtr = &someDerived;    //set bas obj pointer to derived obj
    basePtr->nVirt();          //????
/*
why does a pointer of base type still call base methods when it is
pointing to the address of a derived obj? do base obj pointers
always point to base methods even when pointing to derived obj's?
*/
    basePtr->yVirt();          //????
/*
why should i be surprised that same pointer is calling the yvirt
function since it is pointing to a derived object? shouldn't a
pointer to a derived object also point to that object's members?
*/
    derivedPtr = &someBase;    //ERROR????
/*
i've read that a pointer to derived obj can point to a
base obj. why not here? what gives?
*/
    return 0;
}

Create a music/audio player

by Sismetic at 11:22 AM, 09/01/2010

Hi, thanks for choosing to help me.

I want to do a simple music player, you know, the slider with the seconds you're on, play/pause, stop, open file, show recent files,about and exit. I tried QT's Phonon, but it isn't working, I get a lot of errors trying to compile the example code from qt's official website http://doc.trolltech.com/4.4/phonon-musicplayer.html and the code from the tutorial in the Phonon's official website Urlhttp://api.kde.org/4.0-api/kdelib...onon_tut1.html.

I wanted to know if anybody knows another library/framework on which I can do the music player, and that it doesnt take too long to learn. Im considering Windows programming, but it seems to be a little hard(at least harder than QT), or show me some code of an already made music player, for me to watch it and learn.

Thanks for the help,
Sincerely,
Sismetic

error in installaton visual studio6.0

by exekiel101 at 10:28 AM, 09/01/2010

ive already run the installation wizard and why i always run the main setup the thing that comes out is this "a previous installation of visualsourcesafe at D:visual basic 6.0\VSS\ select yes to replace it with VSS6.0 or no to install and no to its default" 5then i encountered this one "you must first run the installation wizard before running this setup"

help me what to do

Dynamic class overloads

by sinfultom at 10:17 AM, 09/01/2010

Hi there, I'm new to the forum so please be kind :)

I've created a class called node that has a standard constructor and an overload that uses an int as an argument.

class node
{
public:
        node(void);
        node(int inputs);
...
};

I can create an dynamic array of nodes with
node *nodes;
node = new nodes[number];
which works very nicely. But now I want to setup the nodes using the overloaded constructor. I tried
node = new nodes(width)[number];
but that just created a whole load of errors. I realise I could make another function in the node class that could make the changes the overload would've done but I want this to be as neat as possible. Any help would be greatly appreciated.
Thank you, Tom

Filing In Winform c++

by great_learner at 09:40 AM, 09/01/2010

Hi,

Can anybody tell me that how can i open file and write it in winform C++? i have googled alot and searched msdn but could not find appropriate help. I also tried using fstream's objects but they were declared unidentified on winform. what can i just do? what stream class should i use? please also specify its header file.

Any help will be highly appreciated. thanks.

Bitwise operations and binary conversion

by hag++ at 09:22 AM, 09/01/2010

Hi All,

I have been programming for a while, currently a junior CS student. Programming has always felt very natural to me and I pick up new concepts quickly and I generally retain most of what I learn. However, when it comes to converting between Dec/Bin/Hex as well as performing bitwise operations, I have never really been able to retain the process. Also, the problem is that every programming book that I have accumulated over the years always seems to only touch on the subject lightly, like a quick review. I am looking to find some good, in depth and intuitive reading about converting between the three and also mastering bitwise operations. I know this is something that is covered in basic courses but for some reason I have never been able to really master it.

particle detector clustering algorithym

by dcforshaw at 09:04 AM, 09/01/2010

Hi all,

I am currently working analysising silicon pixel detectors for the LHC at my university.

One thing i have to do is to find clusters of signal in a silicon pixel detector.

I have directory of macros which handles the data and getting it ready, not important.

My goals are to create a macro/ algorithym that finds clusters of data, with this i want to:
1) find number of 1 cluster hits, 2 cluster, 3 cluster etc.... on the sensor
2) this info will be made into a histo (not a problem)
3) histo's of 1 cluster, 2 cluster and 3 or more clusters will be filled with the total relevant signal

background:

The sensors i used are silicon pixel, they are very small and are designed for charge sharing, this means that pixels are prone to share there charge with surrounding pixels. this allows for a good resolution.

The sensor is made up of 2048 pixels sensors with 256 read out channels. therefore each channel is attached to 8 pixels. the pixels aren't next to each other they6 are spread out over the sensor in a specific pattern.

pixels connected to channel 1 and 2 arnt next to each other either.

i used a 2D array as a model of the sensor layout. were each element can be thought of as a pixel. each element in the array is filled with the relevant channel for that "pixel"

vectors havnt been used to simpilfy things since a spacial position isnt required merely a position with refference to the other pixels.

The 2D array has the form PIXEL[16][128]
where the signal for each channel is _signal[256]

any help about how to find the clusters is much apreiated

Thx

Data access Layer Design with C++

by evstevemd at 08:52 AM, 09/01/2010

Hi,
I'm trying to develop application with separation of UI/BL/DAL.
I have read a lot of theories and I'm trying to develop a blue print for my application.
I have no problem in UI thing. But I have problem with designing Data Access Layer.
It will basically be a SQLite database backend (I may add other backends as well as XML).
Now I don't know how to write class(es) to do the DAL. So please help me get on it, perhaps with very simple example.

Thanks
uhm sir... the program must be like this...
..awwwhelp me plsss

the rows and columns must input numbers manually

...and the result will be like multiplication table...

the outcome must be like this:



number of rows?: 5
number of columns: 6

input rows: 2 3 5 1 0
input columns: 1 5 7 8 2 3

1 5 7 8 2 3
2 2 10 14 16 4 6
3 3 15 21 24 6 9
5 5 25 35 40 10 15
1 1 5 7 8 2 3
0 0 0 0 0 0 0

returning a 2d array

by Lord_Migit at 08:04 AM, 09/01/2010

hey folks, i have a problem which seems to be reasonably simple but i havnt managed to figure it out yet. Iv read alot of the other threads on this but i still havnt found one that iv both understood and solved my problem. So here goes...

Its concerning returning a member variable, that is a 2d array made within a class, to the program.

//located in the class header file
int**        m_iPopulation;

//located in the class constructor
m_iPopulation = new int* [m_iPopDensity];
for(unsigned short int i=0; i<m_iPopDensity; i++)
        m_iPopulation[i] = new int [m_iChromeLength + 4];

the above all works fine, i can see the population when i fill the array and i can print them to the screen etc. The problem comes when i try to return the above array to the main program.

//located in class header file
inline int**        GetPopulation(){return m_iPopulation;};

//located in the main() program
int** iPopulation = new int* [iPopDensity];
for(unsigned short int i=0; i<iPopDensity; i++)
        iPopulation[i] = new int [iChromeLength + 4];

iPopulation = _pGA->GetPopulation();

when i try to print whats in the array all i get is 1 memory address. and when i debug all i can see is a single entry in the array.

not sure what im doing wrong and i cant find anything else on the fora to help me, so any help is greatly appriciated.

thx!

c++ download

by MivanF at 07:20 AM, 09/01/2010

where i can download the c++ free???? :S

multiplication table HARDER

by exekiel101 at 06:55 AM, 09/01/2010

uhm sir... the program must be like this...
(<<snip>>..awwwhelp me plsss

the rows and columns must input numbers manually

...and the result will be like multiplication table...

the outcome must be like this:
number of rows?: 5
number of columns: 6

input rows: 2 3 5 1 0
input columns: 1 5 7 8 2 3

1 5 7 8 2 3
2 2 10 14 16 4 6
3 3 15 21 24 6 9
5 5 25 35 40 10 15
1 1 5 7 8 2 3
0 0 0 0 0 0 0

code compiling but not giving desired result

by Rajkamalwin at 06:43 AM, 09/01/2010

//i am writing a code that read from a file and store words in an character array but //in the wriiten by me,it is compiling but not extracting words in the array.
#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
using namespace std;

int main()
{
ifstream fin;
char ch;
int j=0;
string line;


//reading from file.....
fin.open("rajkamal");//rajkamal is a valid file.
while(fin)
{
getline(fin,line);
}
cout<<"\n"<<line;
fin.close();

//putting data into an array from a string.
cout<<"\n"<<line;
char *a=&line[0];
cout<<endl;
cout<<a<<"******"<<endl;
cout<<a[0]<<a[1]<<a[2]<<a[3]<<endl;

int r=0,c1=0,i=0;
char word[10][10];
for(i=0;i<line.length();i++)
{
if(a[i]=' ')
{
word[r][c1++] = line[i];
}
else
{
word[r++][c1]=0;
c1=0;
}
}
word[r][c1]=0;


for(i=0;i<=r;i++)
{
cout<<word[i]<<"\n";
}

return 0;
}

Need help on this one. :(

by udtohan_noriel at 06:27 AM, 09/01/2010

Guys, could someone help me to make a program that will display this not using if-else statement.

I want to learn how to make it using for loop statement and any statement that will make this program short. I need 1 Program using for loop and another program but not if-else.

Sample Output:
_____________________________________________________________

Enter a number(0-25) : 7(Example of inputted number)

0 - Zero
1 - One
2 - Two
3 - Three
4 - Four
5 - Five
6 - Six
7 - Seven

_______________________________________________________________

Thanks a lot. ;)

cryptography program

by s-pika at 02:50 AM, 09/01/2010

i've this code, and when i run it, it produce garbage
how to solve it????

#include <stdio.h>
#include <string.h>
#include <stdbool.h> // using bool data type

void function (void);
char encode(char);
char decode(char);
void changeSecretCode(char, char);

  char code[27] ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
  char secretCode[27] = {'Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A'};


int main ()
{
    function();
   
    system("pause");
    return 0;
}//end of main function

char encode(char c)
{
switch (c)
{
    case 'A' :  return secretCode[0]; break;
    case 'B' :  return secretCode[1]; break;
    case 'C' :  return secretCode[2]; break;
    case 'D' :  return secretCode[3]; break;
    case 'E' :  return secretCode[4]; break;
    case 'F' :  return secretCode[5]; break;
    case 'G' :  return secretCode[6]; break;
    case 'H' :  return secretCode[7]; break;
    case 'I' :  return secretCode[8]; break;
    case 'J' :  return secretCode[9]; break;
    case 'K' :  return secretCode[10]; break;
    case 'L' :  return secretCode[11]; break;
    case 'M' :  return secretCode[12]; break;
    case 'N' :  return secretCode[13]; break;
    case 'O' :  return secretCode[14]; break;
    case 'P' :  return secretCode[15]; break;
    case 'Q' :  return secretCode[16]; break;
    case 'R' :  return secretCode[17]; break;
    case 'S' :  return secretCode[18]; break;
    case 'T' :  return secretCode[19]; break;
    case 'U' :  return secretCode[20]; break;
    case 'V' :  return secretCode[21]; break;
    case 'W' :  return secretCode[22]; break;
    case 'X' :  return secretCode[23]; break;
    case 'Y' :  return secretCode[24]; break;
    case 'Z' :  return secretCode[25]; break;

    } // end switch
 } //end function encode


char decode(char c)
{
  bool found = false; int m=0;
  char tt = c ;

  while (!found && m < 26)
  {
            if (c == secretCode[m])
                  {
                      found = true;
                      tt = code[m];
                  }
        m++;
  }
 
  if (!found)
        printf("Invalid code!");
  return tt;

 } //end function decode

void changeSecretCode(char ori, char baru)
{
  bool found = false;
  int m=0;
 

  while (!found && m < 26)
  {
            if (ori == code[m])
                  {
                      found = true;
                      secretCode[m] = baru;
                  }
        m++;
  }
} //end function changeSecretCode

void function (void)
{
  int menu;
  char baru,ori;

  char text[100]; // input data
  char outText[100]; // output data
     
  int j,i;
   
   
      printf("Please choose your menu\n");
      printf("  1. Encode\n");
      printf("  2. Decode\n");
      printf("  3. New Secret Code\n");
      printf("  4. Change Secret Code\n");
      printf("  5. Exit\n");
     
 do
 {
  printf("\n\nSelect Option : ");
  scanf("%d",&menu);
     
       
    if (menu==1)
            {
              printf("Enter message to encode : ");
              fflush(stdin);
              gets(text);
              j = strlen(text);
           
              for (i=0; i < j; i++)
                  {
                      outText[i] = encode(text[i]);
                  }
           
              printf("%s is encoded as %s \n",text, outText);
            }


    if (menu==2)
            {
              printf("Enter message to decode : ");
              fflush(stdin);
              gets(text);
              j = strlen(text);

              for (i=0; i < j; i++)
                  {
                      outText[i] = decode(text[i]);
                  }

            printf("%s is decoded as %s \n",text, outText);
            }
   
   
    if(menu==3)  // print the array
            {
              printf("\nSecret Code\n");
             
                  for(i=0;  i<26; i++)
                          printf("%c ",code[i]);
                         
                  printf("\n");

                  for(i=0;  i<26; i++)
                      printf("%c ",secretCode[i]);
                     
              printf("\n");
       
            }
           
    if(menu==4) // change the code
            {
              printf("Replace secret code for : ");
              fflush(stdin);
              scanf("%c",&ori);
                   
              printf("New code for %c :  ", ori);
              fflush(stdin);
              scanf("%c",&baru);
             
                    // change to new secret code
              changeSecretCode(ori, baru);
             
              printf("\nNew Secret Code\n");
             
              for(i=0;  i<26; i++)
                      printf("%c ",code[i]);
                     
                  printf("\n");

              for(i=0;  i<26; i++)
                    printf("%c ",secretCode[i]);
                   
                    printf("\n");

            }
   
     
 }while (menu==1 || menu==2 || menu==3 || menu==4);
   
}  //end of function

C++ Doubts???

by johnsign11 at 02:44 AM, 09/01/2010

Hello friends
Can anyone tell me Why and How to use vector in C++ ????
Making a sudoko game in c++

Setting the console window size

by sudoku43 at 01:36 AM, 09/01/2010

can anyone teach me how to set the size of console window?

storing char[], int16, int32 in double array

by AutoC at 23:33 PM, 08/31/2010

Hi,

Here's my scenario. I am given records and the datastructure of each column in the records at runtime. A sample looks like this,
char[] | int16 | int32 | double
abcd  | 2    | 96    | 1024
ghi    | 3    | 104  | 2048

I cannot predefine a structure because I dont know what data types I am gonna be given.How can I store the records? I was thinking of declaring a multidimensional double array and typecasting all the records and then casting back whenever necessary. Does this seem sensible? Is there a better solution?

Need help in writting a functio.

by grahf23 at 23:20 PM, 08/31/2010

Hi, i'm supposed to write a function, countGrade that takes in the Grade and find the number of students that have this grade. This value is returned to the calling program. The function prototype is int countGrade(char). Currently all i have written is this.
Seem like there's something wrong with my function but i have no idea how to fix it. Any help would be appreciated. Thanks in advance!
#include <iostream>
#include <string>
using namespace std;

struct markRec {
        string id;
        string name;
        double tt, fe, score;
        char grade;
};

struct markRec myMark[] = {
        {"B001", "Tan Choon Seng", 34.0, 67.0, 53.8, 'D'},
        {"B002", "Anne Smith", 79.0, 88.2, 83.6, 'A' },
        {"B003", "Alice Lim", 56.0, 45.0, 49.4, 'F' },
        {"N003", "Alan Phang", 67.0, 87.0, 79.0, 'B'},
        {"N005", "Ho Tock Seng", 60.0, 67.0, 64.2, 'C'},
        {"N0056", "Tan Bee Hoon", 79.0, 88.1, 83.6, 'A'},

};
//The main program
int main (){
        char c;
        cout << "Enter grade : " ;
        cin >> c;

        countGrade (c);

        return 0;
}
//Function
int countGrade (char c)

{
  char grade;
  int count;

 
  for ( count = 0; count < grade.size; ++count ) {
        if (grade == c )
        cout << "The number of students that have grade" << c << "are" << count << endl;
  }
 
  return count;
}
bool
I8051::Hex2Short(const char* buf, unsigned &val)
{
int i;

if( sscanf(buf, "%x", &i) != 1 ) {
cerr << "Error: hex file error." << endl;
return false;
}
val = i;
return true;
}

//----------------------------------------------------------------------------

bool
I8051::Load(const char* buf, unsigned char* rom, unsigned& prgSize)
{
unsigned temp;
unsigned len, base, type;
unsigned char checksum = 0;
char hex[16];

if( buf[0] != ':' ) {

cerr << "Error: hex file error." << endl;
return false;
}

hex[0] = buf[1];
hex[1] = buf[2];
hex[2] = 0;
if( !(Hex2Short(hex, len)) ) return false;

hex[0] = buf[3];
hex[1] = buf[4];
hex[2] = buf[5];
hex[3] = buf[6];
hex[4] = 0;
if( !(Hex2Short(hex, base)) ) return false;

hex[0] = buf[7];
hex[1] = buf[8];
hex[2] = 0;
if( !Hex2Short(hex, type) ) return false;

if( type == 1 ) return true;

if ( (base+len) > (prgSize) ) {
(prgSize) = base + len + 2;
}

if( (prgSize) >= RomSize || (base+len) >= RomSize ) {
printf("program too large\n");
exit(1);
}

for(unsigned i=0; i<len; i++) {
hex[0] = buf[ 9 + i * 2];
hex[1] = buf[10 + i * 2];
if( !Hex2Short(hex, temp) ) return false;
rom[base + i] = (unsigned char)temp;
}

//-----------------------------------------------------------

for(unsigned i=0; buf[i * 2 + 1] && buf[i * 2 + 2]; i++) {

hex[0] = buf[i * 2 + 1];
hex[1] = buf[i * 2 + 2];
unsigned temp;
if( !Hex2Short(hex, temp) ) return false;
checksum += (unsigned char)temp;
}

if( checksum != 0 ) {

cerr << "Error: checksum failed." << endl;
return false;
}
return false;
}





this is a part of the whole code for simulator of 8051 . when i compile it , it compiles successfully with DEVC++ ide, but at the run time it shows inifinite times or the "Error:hex file error" . I cant understand how to solve this . I want your help to solve this . plz help me soon.Thank you .

c++ string substr query

by AutoC at 22:07 PM, 08/31/2010

Hi,

I have a string that looks like this

\\x\\y\\z-Select * from x where y=z

I need to split this at the '-' into two strings. When I use substr as,
string s = "\\x\\y\\z-Select * from x where y=z";
size_t p = s.find("-");
if(p!=string::npos)
  string query = s.substr(p+1);

but how do i get the part before the position?

[HELP] Help me to build this program by using Turbo C++

by afizaex at 21:19 PM, 08/31/2010

Help me to build this program by using Turbo C++, thank you;

User will enter car type and package of car based on the following;

-------------------------------

TYPE...PACKAGE..PRICE.........TAX
_______________________________
CAR1.......a............24000.........150%
.................b............28000.........150%
_______________________________
CAR2........c............35000.........200%
.................d............37000.........200%
.................e............41000.........200%
-------------------------------

This program will calculate new price for the type of cars after being taxed.
This program will display type of car, package and the price that has to paid by the customer.
This program will continue until user request to stop.

At the end; the program will display:
-number of customer for CAR1 type
-number of customer for CAR2 type
-total sales for CAR1 type
-total sales for CAR2 type
-total sales for all cars

Programming a Visual Timer

by shrublet at 19:39 PM, 08/31/2010

Hello, all! :)

Let me preface this by saying that I am a computer science student with only a rudimentary introduction to C++ so far, having worked mainly in Java up until now. I apologize if this is an overly simplistic question.

A relative of mine has asked me to program a visual timer for them. I could probably do it in Java but I figured giving it a shot in C++ would let me practice a bit. Anyways, I am not even sure where to start insofar as graphics go.

The idea behind the timer is that the user is able to input a time (of course) and the clock will tick down in front of a circle that fills up in a pie-like manner (if that makes any sense at all!). I think that this is the basic idea for the circle animation: http://download.cnet.com/VitalSmarts...-10990391.html (The rest of it would be different, of course, that's just a reference for the circle and I'm not making it for commercial use.)

As I said, I've only done graphics and animation in Java, so I am at a total loss as to what I could research. I'm aware of OpenGL for graphics but I don't know if this would be overkill, if there is something better suited, etc. Any point in the right direction would be greatly appreciated.

Thank you, everyone!

Strings of characters

by miznogud at 18:44 PM, 08/31/2010

The insruction is create a program that asks for two input srings until the character 'x' is encountered. For each input string display as output its length, its reverse and the concatenation of reversed inputs (see output below).

Sample output:

Enter 1: Hellox
enter 2: Goodbyex

the inputs are: Hello and goodbye
the lengths are: 5 and 7
the reverse are: Olleh and eybdoog
concatenation: Olleheybdoog

do you like to repeat asking input?(y/n)y

Decimal to binary conversion trouble

by bmos31 at 18:27 PM, 08/31/2010

I'm having trouble even getting started with this problem. I've tried looking at other examples, but I'm completely stuck.

The question and my code(not even sure if im on the right track) is as follows:

Write a function called decToBinaryString that recieves a non-negative int and returns a string that is a binary representation of the number input.
tips - concatenate strings together
test odd/even using %
write a main() that test the code
#include<iostream>

using namespace std;

void intToBinaryString(unsigned long int, char *);

#define ARRAY_SIZE 1000

int main()
{
    unsigned long int number;
    char binary[ARRAY_SIZE];
    int i;

    cout << "Enter a non-negative integer to convert to binary: ";
    cin >> number;
    intToBinaryString(number, binary);
   
    cout << "Binary representation: ";
    for(i = 0; i < binary
    system ("pause");
    return 0;
}

void intToBinaryString(unsigned long int num, char *bin)
{
    int remainder;
    if(num%2 == 0)              //even
    {
        do
        {
            remainder = num%2; 
        }while(num > 0);
       
   
    else                        //(nonNeg%2 != 0) odd
                   
}

guess the nunmber!

by xiansen at 18:15 PM, 08/31/2010

You are to write a program that plays the game of “Guess the Number”. Your program is to randomly choose a three-digit number, allow the user to guess, provide feedback indicating if the users’ guess was too high or too low, and count the number of guesses the player makes.

Your program should provide and make use of functions:

void secretNum (int& num)
Determines the secret number to be used, passing back by reference parameter.

bool checkGuess(int guess, int answer)
This function returns true if ‘guess’ is equal to ‘answer’, and false otherwise.

void guessResponse(int guess, int answer)
This function prints a message indicating if the ‘guess’ is lower or higher than the ‘answer’

void countResponse(int count)
If count is less than 10, this function prints “You must know the secret”.
If count is equal to 10, this function prints “You got lucky”.
If count is greater than 10, this function prints “You should be able to do better than that”.

Your main function will:
Determine the secret number (use the stdlib function rand for this)
Ask the user to guess
If the user did not guess correctly
Provide feedback for the guess
Repeat the above until the user guesses correctly
Output the guess count and feedback indicating how the user did

This should be repeated for 10 problems. Prior to exiting, the program should print the lowest and highest number of guesses that occurred.

* Constant variables should be provided to store any number, which would appear in the code so that these can be easily changed if, need be.


Below is what i have so far. I am getting an error when i tried to compile it. I don't know where I have made an error. I would really appreciate it if someone could help me point out what I am doing wrong.
// Pro2a.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void secretNum(int&);
void guessResponse(int guess, int answer);
void countResponse(int count);

int main()
{
        int number;
        srand(time(0));
        secretNum (number);

        int tries = 0, spec;

        cout << "\tWelcome to Guess My Number\n\n";

        //Guessing Loop
        do
        {

                cout << "Enter a guess:";
                cin >> spec;
                ++tries;
                guessResponse( spec, tries);
       
        } while (spec != number);
        countResponse(tries);
        cout << "\nyou got it! You got it in" << tries << "guesses!\n";
        system ("pause");
return 0;
}

void secretNumber(int &num)
{
       
        num = rand() % 1000 + 1;
}

void guessResponse(int guess, int answer)
{
        if (guess > answer)
                cout << guess << " is too high!\n\n";

        if (guess < answer)
                cout << guess << "is to low!\n\n";
}

void countResponse(int count)
{
        if (count > 10)
                cout << "you should be able to do better than that";

        if (count < 10)
                cout << "you must know the secret";
       
        if (count = 10)
                cout << "you got lucky";
}

Need help with binary representation in C++

by jumpdlite at 17:20 PM, 08/31/2010

i am to write a C++ program to output the binary (base – 2) representation of a decimal integer. the program should accept a positive integer from the user. After verifying that the input is valid, the program should call a function named toBin, which outputs the binary representation of the number.

The function toBin must not be a recursive function.

I am a beginner in C++.I don't know where to start and don't really understand the question. It would be really helpful if someone could show me an example of what i am supposed to do. Thank you.
Hey
I've only been coding for a couple of days
and I got this code im working on
for some reason the computer only guesses the number 42 instead of a random number
can someone help me?

Heres the code:

/*========================================================================\
|This is basically the guess my number game                              |
|But the roles are reversed, well I'm going to try it anyway              |
|-------------------------------------------------------------------------|
|31/08/2010 - 9:00 started                                                |
|31/08/2010 - 9:51 finished                                              |
|Its slightly flawed as in the random generator only sticks to one number |
|once I learn another method I will update this script                    |
|-------------------------------------------------------------------------|
|By Chris Forgeard                                                        |
|Copyrighted 31/08/2010                                                  |
\========================================================================*/

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

int main()
{
   
//first ill set up the random number generator etc.
        int number = rand() % 100 + 1;
        int tries = 0;
        char right = 'n';
       
        cout << "Welcome HP MINI, guess my number!" << endl;

//The game loop
        while (right == 'n')
        {
            cout << "Is it " << number << "?" << endl;
            cout << "(y/n)" << endl;
            cin >> right;
           
            if (right == 'y')
            cout << "Yes HP MINI, that is right!" << endl;
           
            if (right == 'n')
            cout << "Sorry HP MINI, that is wrong!";   
            ++tries;
        }

//The end scene       
        cout << "Congratulations HP MINI!" << endl;
        cout << "You did it in " << tries << " tries!";
        cin >> right;
       
        return 0;
}

Problem opening files in Windows Vista

by caribedude at 16:54 PM, 08/31/2010

Hi, I'm having some problems with this bit of code. I need to randomly open some files that have numbers as their filenames. i came up with this snippet to be able to open them from numbers 0 to 99. The code should randomly pick a number and try to open a file with that name, if the file does not exist, it lowers the range of numbers it can pick until reaching 10. I ran this on Ubuntu and it worked perfectly, but when I switch to Windows the loop never ends. If instead of using a random filename I use, for example filename="Synthesis//2.txt"; the program runs fine. i don't know why the code works on Ubuntu but not in Windows Vista. Any help is apreciated.

std::string Synthesis::itoa(int number)
{
    std::stringstream word;
    std::string output;
    word<<number;
    word>>output;
    return output;
}
int Synthesis::Load( int Level){

    int disponible=100; // las sintesis disponibles del 0 al 99 en ese level
    ifstream tempsynth;
    string filename;


    int SynthNumber;

        do {
        SynthNumber = rand() % (disponible)+ Level*100;
        filename="Synthesis//"+itoa(SynthNumber)+".txt"; //itoa is a custom funtion that return a string
       
        Log<<filename.c_str()<<"\n"; //this prints the filename into a file
        tempsynth.open(filename.c_str());//,ios::binary);
       

        if (!tempsynth && disponible>=10)
            disponible=disponible-3;  //como no van a haber 100 sintesis se baja la busqueda hasta que hallan
                                    }

        while (!tempsynth );

How do I get this loop to stop and create a cancel function

by chris forgeard at 16:49 PM, 08/31/2010

Here is my code
excuse me if it seems a bit off
i've only been coding for a day :)
What I want it to do is in the comments at the top


/*======================================================================
IN THIS PROGRAM I WILL TRY AND SCRIPT A CONVENTIONAL CALCULATOR
WITH THE USER ENTERING THE NUMBERS THEY WISH TO MULTIPLY ADD ECT.
ALSO I WILL MAKE A CANCEL FUNCTION WHICH ERASES OR LOOPS THE PROGRAM.
JUST TO CLARIFY THIS PROGRAM IS COMPLETELY MADE UP AND WAS MADE BY ME
WITH NO HELP WHATSOEVER.
------------------------------------------------------------------------
31/08/2010 13:00 - STARTED
31/08/2010 15:28 - FINISHED
HAS SOME FLAWS IF YOU TYPE 'C' INTO WHERE IT ASKS FOR A NUMBER IT GOES CRAZY.
ALSO SOME FUNCTIONS ARE NOT COMPLETE SUCH AS THE CANCEL FUNCTION, I WANT
IT TO CLOSE THE PROGRAM WHEN 'C' IS PRESSED.
ALSO THE FUGTURE MODULUS FUNCTION IS YET TO BE CREATED.
------------------------------------------------------------------------
31/08/2010 - 16:24 STARTED
31/08/2010 - 16:34 FINISHED
STILL CAN'T GET FUNCTIONS TO WORK SUCH AS MODULUS AND CANCEL.
------------------------------------------------------------------------
BY CHRIS FORGEARD
========================================================================*/

#include <iostream>
using std::cout;
using std::cin;
using std::endl;


//I CHOSE DOUBLES JUST INCASE USER CHOOSES TO USE DECIMAL PLACES
double number;
double number_2;
char cancel = 'c';
double result_times;
double result_add;
double result_minus;
double result_divide;

int main()
{
    cout << "Welcome to the calculator!\n" << endl;
   
//=====================================================================
//THE CALCULATOR LOOP
    while (cancel == cancel)
    {
    cout << "Please begin by entering your first number\n" << endl;
    cin >> number;
    cout << "Now enter your second number please\n" << endl;
    cin >> number_2;

//---------------------------------------------------------------------
//OPTIONS   
    cout << "Now what would you like to do?\n" << endl;
    cout << "1: multiply" << endl;
    cout << "2: addition" << endl;
    cout << "3: minus" << endl;
    cout << "4: divide"<< endl;
    cout << "5: cancel" << endl;
    cout << "6: coming soon (modulus)\n" << endl;
//---------------------------------------------------------------------
//SETTING UP CHOICES 
    int choice;
    cout << "\n\nChoice: ";
    cin >> choice;

//---------------------------------------------------------------------
//THE SWITCH PROGRAM (DEPENDS ON CHOICE WHAT PATH PROGRAM TAKES) 
    switch (choice)
    {
    case 1:
        cout << "You have chose to multiply your numbers" << endl;
        result_times = number * number_2;
        cout << "Your answer is: " << result_times << endl;
        break;
    case 2:
        cout << "You have chose to add your numbers" << endl;
        result_add = number + number_2;
        cout << "Your answer is: " << result_add << endl;
        break;
    case 3:
        cout << "You have chose to take away your numbers" << endl;
        result_minus = number - number_2;
        cout << "Your answer is: " << result_minus << endl;
        break;
    case 4:
        cout << "You have chose to divide your numbers" << endl;
        result_divide = number / number_2;
        cout << "Your answer is: " << result_divide << endl;
        break;
    case 5:
        cout << "You have chose to cancel!" << endl;
        break;
             
    default:
            cout << "I'm sorry but that option is not available!" << endl;
            break;
    }
}

//END OF LOOP
//================================================================================

    return 0;
}

VC++ Headers

by civus at 16:14 PM, 08/31/2010

Hi Guys, I'm wondering if someone can help me out with a problem I've been having with VC++. I'm obviously just beginning to learn C++ and have been working with CodeBlocks and VC++ 2010 Express. My problem is that the following code compiles in CodeBlocks but gives me numerous errors and dies with VC++ (for the sake of space, I've simplified it as much as I can down to the problem area)...

In Main.cpp:

#include "Head.h"

int main()
{
cout << strFunction(12) << endl;
return 0;
}

In Main2.cpp:

#include "Head.h"

string strFunction(int x)
{
return "blah blah blah.";
}

In Head.h:

#pragma once
#include <iostream>
using namespace std;
string strFunction(int x);

Since I'm only dealing with two source files and a miniscule program, obviously a header here isnt really necessary, but I really want to learn how to work with them for later use. The maddening thing about this is:

1) The header works for some things. I use it to #include <iostream> without any trouble, I can declare global variables just fine, etc. Its really just something with any function prototypes I put in there.

2) Function prototypes work fine if I just manually copy the prototype into the other source file. I only get the errors when I reference it in the header.

Here is (a small part) of the errors I receive when I try and run the above project:

Main.cpp
1>c:\users\michael\documents\visual studio 2010\projects\project7\project7\main.cpp(5): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(726): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(764): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'

----

I'd be tremendously appreciative of any help you guys could offer me. I've tried everything I could think of and experimented with everything I can think of but nothing seems to work. FWIW, I've tried this code in a completely empty VC++ project as well as inputting it into their custom made console app. Same errors.

I'm at my wits end. Please help.

(p.s. first post, great to be on board here).

beginner problem with fuction return

by frogboy77 at 14:38 PM, 08/31/2010

trying to write a fuction to work out the GCD of two numbers
seems to run ok but the return is incorrect
any help much appreciated

#include <iostream>
#include <cmath>

using namespace std;

int g_c_d(int a,int b);

int main()
{
cout<<g_c_d(2871,4060);/*test example*/


cout<<endl;
system("pause");/*been advised not to use this but at my level well hey!*/
return 0;
}

int g_c_d(int a,int b)
{
int c;
c=abs(b-a);
cout<<a<<" "<<b<<" "<<c<<endl;/*put this in to check it was going ok*/
if(c==0){return a;}
if(b>a){b=a;}
a=c;
g_c_d(a,b);
}

returns 4249024 instead of 29

sorry this may be double post just new to this
didnt know wether it should be code snippet or discussion thread

beginner GCD function problem

by frogboy77 at 14:31 PM, 08/31/2010

Hey there,
this code was supposed to work out th GCD of 2 numbers
added cout line in function and code seems to be running fine
but it returns 4249024 instead of 29
this is probably a basic error on my part but can anyone tell me why?
thanks for any help
as is quite clear am a beginner at this.

iterators

by tennis at 10:35 AM, 08/31/2010

say iter1 and iter2 are both iterators

*iter1++=*iter2++;

what does this line means? Can anybody help explain? ++ and * which is done first?
thanks

Searching file system using Visual C++ forms?

by Member 784689 at 08:53 AM, 08/31/2010

I'm trying to make a simple visual C++ app that searches directories in the file system based on the user's selection.

The form view is attached.

Attached Thumbnails
Click image for larger version

Name:	Form.jpg
Views:	N/A
Size:	26.5 KB
ID:	16998  

writing into binary file

by senthamizh at 08:39 AM, 08/31/2010

I have a problem when i am writing into files in a binary format.I have noticed that, it writes two times into the file. Here i have attached the code.

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class bank
{
protected:
char receive[20];
public:
}

int main()
{
fstream file;
strcpy(receive,"hello");
file.open("binary.my",ios_base::in | ios_base::out | ios_base::binary | ios_base::app);
file.write(reinterpret_cast<char*>(&receive),sizeof(receive));
file.close();
return 0;
}

data structures

by dflatt at 08:06 AM, 08/31/2010

I can't decide what data structure to use for a program I'm making.

the program I'm making is a football table, the variables used so far are;
string team;
int played = 0, goalsfor = 0, goalsagainst = 0, goaldiff = 0, win = 0, draw = 0, lose = 0, points = 0;

I was originally thinking of using a vector as I can resize it when I set it up. the table is organised by the points initialy and in the event of a tie goal difference is used.

I was thinking of using quicksort to organise it.

any advice?

Odd screen capture on window update

by PixelExchange at 07:43 AM, 08/31/2010

I have recently stumbled upon a program that permits a person to have an animated image "dance" across the users' current active window. The problem is.. something very strange occurs when I have this animated image dancing across MY program's main window.
For some reason, whenever I either maximize or minimize MY program's main window (while this animated image is dancing across my screen), whatever frame within the images' animation sequence that happened to be playing when I maximized/minimized my screen, gets "imprinted" on MY main program's window.

Ex:
If the animated image happened to be jumping when I maximized my window.. a jumping character would be imprinted on my main window's screen (wherever that image was jumping at at the time of the window's maximization).

The problem is.. the "imprinted" image.. does NOT go away on my main window's screen!

In order to get rid of that imprinted image.. I've tried Invalidating my window's entire screen on window maximization (which works some of the time) but some times.. the screen invalidation does NOT get rid of the imprinted image.

The only method I've found that actually gets rid of the imprinted image EVERY time.. is to drag my program's window off screen.. and pull it back on the desktop again.. which does an automatic screen invalidation, and repaints everything on the screen when the window becomes visible again.

My question is.. WHY isn't a simple screen invalidation getting rid of the imprinted image every time I force a screen invalidation?

Please Note: Yes, I am sure the screen is being invalidated when it is supposed to be, as the entire screen "flickers" on screen invalidation. (But the imprinted image is still there!)

Need some help

by Ritesht93 at 07:31 AM, 08/31/2010

Hello!!
Can u all tell me what are different types of apps......lyk console apps,win32 apps etc.....what is basic difference between win32 n console apps..............
THANKS IN ADVANCE!!:)

C++ Library Training Needed

by Michael_Grumbac at 05:01 AM, 08/31/2010

I need to take a class on using C++ Libraries.
Something that's about 3 months in duration, with some sort of a test at the end.
I could easily just go to google and start there, but I was afraid that I would just get a zillion classes, without any way of knowing what is "shinola" and what is s***thing else.
Any suggestions for high quality, online learning that fills this bill would be greatly appreciated.

Thanks,
Mike

Serialization of dynamic data over socket

by AutoC at 04:08 AM, 08/31/2010

Hi,

I have a struct that looks like this
struct Info
{
  char **field_names;
  double **data;
  int *cindex;
}
I have to serialize an object of this struct and send it over a socket and deserialize at the other end. What is the best option for this?

guessing game program

by Empireryan at 23:02 PM, 08/30/2010

I am writing code for a guessing game program. The game is supposed to generate a random number, 3 digit number and let the user guess what it is, providing feedback for every wrong input. It is also supposed to perform 10 iterations, keeping track of the number of guesses. It then should use this record to determine the fewest guesses it took to figure out the number. I have the program set to execute 2 iterations for ease of troubleshooting. It also provides the secret number generated for reference.

I have been having trouble implementing a method of logging the number of guesses it took per random number generated. I tried a function tied to int &count inside of guessCollector( ) and a few permutations of. All I can manage is to get the code to output the number of guesses during the last iteration of the game. What would be the best way to go about this? Any ideas are greatly appreciated. I've considered using an array, but have not tried tom implement one yet. We are not allowed to use global variables.
#include <iostream>
#include <time.h>

using namespace std;

void secretNum(int &answer);
//function to generate a random number from seed

bool checkGuess(int guess, int answer);
//used to check operator's guess

void guessResponse(int guess, int answer, int count);
//provides feed back to the user; tells whether guess is too high or low

void guessCritique(int count);
//rates user based on number of guesses

void guessCollector(int &guess, int &count, int answer);
//collects guess from user

int tracker(int count);
//score keeper


void returners();
//function to repeat the sequence of functions 10 times, and count the fewest number of guesses.


int main ()
{
       
    srand(time(0));
       
        returners();
       
        return 0;
}

void secretNum(int &answer)
{
        int num = rand()%899+100;
        answer = num;
}

bool checkGuess(int guess, int answer)
{
        return (guess == answer);
}

void guessResponse(int guess, int answer, int count)
{
        if (guess < answer)
        {
                cout << "too low\n";
        }
       
        if (guess > answer)
        {       
                cout << "too high\n";
        }
       
        if (checkGuess(guess, answer))
        {
                cout << "correct! \n";
                guessCritique(count);       
        }       
}       


void guessCritique(int count)
{
        if (count < 10)
                cout << "You must know the secret\n";
        if (count == 10)
                cout << "You got lucky\n";
        if (count > 10)
            cout << "You should be able to do better than that\n";
        cout << endl;
}       

void guessCollector(int &guess, int &count, int answer)
{
        count = 0;
       
        int input;
        do {
        cin >> input;
        count++;
        guess = input;
               
        guessResponse(guess,answer,count);
       
        } while (!checkGuess(guess,answer));
       
               
}

int tracker(int count)
{        int placeh, tracked = 10;
        placeh = count;
       
        if (placeh < tracked)
        {
                placeh = count;
        }
       
        return placeh;
}       

void returners()
{
        int answer, guess, count;

        int tally = 1;
        for (tally <= 2; tally <= 2; tally++)  //change to 10
        {
        secretNum(answer);
       
        cout << answer << endl;                //DELETE. used during runtime to check random number
       
        guessCollector(guess, count, answer);
                tracker(count);       
        }
               
               
}

Casting problem

by Sinaru at 20:16 PM, 08/30/2010

I have two classes and one of them is inherited from the other class.
Class Person - used to store first name and last name of a person. The data members are protected.
Class Candidate - used to store votes of an election, and this is inherited from Person class so that I can store name of the candiadate.

I have overloaded these operators in Person class : ==, !=, <, <=, >, >=

I have also overloaded the same operators in Candidate class too but the definision are same because you can only use the name of the candidate to compare. So rather than copy and paste the same code, I used static_cast. It worked but I wonder is it bad to do like that?

Ex:
bool Candidate::operator ==(const Candidate& right) const
{
    //return (firstName == right.firstName && lastName == right.lastName);
    // Rather than the above, I used this...
    return (static_cast<Person>(*this) == static_cast<Person>(right));
}

Function calls

by totalwar235 at 19:41 PM, 08/30/2010

this questions may be vague, but how many functions can you open up through function calls without ending the function. and example would be...
int FunctionOne();
int FunctionTwo();
int FunctionThree();
int FunctionFour();
int FunctionFive();

int main()
{
  FunctionOne();

  return 0;
}

int FunctionOne()
{
  FunctionTwo;

  return 0;
}

int FunctionTwo()
{
  FunctionThree;

  return 0;
} //ect...

what i am asking is how many times should you be able to do this before the program does not run the next function.

*using visual C++ 2008 EE
*i have the same problem but my real code is 12 pages long if printed and has 5 functions runnning

Need a function 2 "PAUSE" and "RESUME" execution of a prg

by Ritesht93 at 18:25 PM, 08/30/2010

Hey guys!!
i m a student.....n tryin 2 make a game in C++.....game is goin on very well but i hav a question.
i m using borland c++ 3.0 compiler....i hav 2 necessarily use this bcoz v hav d same compiler at high skool.....i'll start using d latest within few weeks.....but i hav to finish dis game within 1/2 a month.....i hav created 2 buttons named as "PAUSE" AND "RESUME"....
nw i need dat ....when i click these buttons....they must do d functions at tym of execution.....i.e if i click pause......the game or rather the execution must be PAUSED.....n if i resume.....the game(i.e execution) must start from where i paused......is there any system function to pause and resume...at tym of execution....if so plzzz let me kno....:-/....
THANKS IN ADVANCE!!

Help: To make all combinations of binary sequence

by The_Prince at 17:09 PM, 08/30/2010

Hi, I have a problem which has been puzzling me for a few days. i have been trying it with vectors and characters but will not work for me. Imagine an "ON" "OFF" binary sequence. I want to compute all combinations of that sequence of length N say.

e.g sequence 001011 of length 6, but want all possibilities arising of length 6

I was thinking about using the <BITSET> class and defining for example

std::bitset<100>

Is this the best way for a sequence of "ON" "OFF" code? Then from here what is the best way to make sure all the possibilities of the sequence can be generated?


(( On a side note, I can't have for instance "std::bitset<N>" where N is user defined or defined elsewhere. The error is 'expression must have a constant value' so I think its something to do with address?))

Thanks for your time in reading if you have gotten this far.

problems with strings

by David_Omid at 16:41 PM, 08/30/2010

Hey guys, I was wondering if any of you could help me with some stuff which may seem obvious to you but I'm a beginner.

I'm making a calculator and have reached the part where I am making the buttons change the string on the calculator's "screen".

The way I am doing this is by getting the current line of numbers as a string and then converting the number pressed into a string and then adding the two strings together to form the new calculator display, I then want to display that string.

After reading some books and looking online I thought the best way of doing this would be to use string streaming, so I have made the following:

if(ButtonType == 1) // Numerical buttons processed here
                        {
                                CurrentInputString = "";
                                CurrentInput = 0;
                                CurrentInput = ButtonNumber;
                                InputOutputStream << CurrentInput;
                                InputOutputStream >> CurrentInputString;
                                InputOutputStream.str("");
                                InputOutputStream.clear();

                                InputOutputStream << TotalInput;
                                InputOutputStream >> TotalInputString;
                                InputOutputStream.str("");
                                InputOutputStream.clear();

                                InputOutputStream << TotalInputString << CurrentInputString;
                                //TotalInputString += CurrentInputString;
                                InputOutputStream >> TotalInput;
                                InputOutputStream << TotalInput;
                                InputOutputStream >> TotalInputString;
                                InputOutputStream.str("");
                                InputOutputStream.clear();
                                this->InputLabel->Text = Convert::ToString(TotalInput);

                        }

I had problems setting the text as "TotalInputString" and got these compiler messages:

Quote:

error C2664: 'void System::Windows::Forms::Control::Text::set(System::String ^)' : cannot convert parameter 1 from 'std::string' to 'System::String ^'
1> No user-defined-conversion operator available, or
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Therefore I decided to change it by converting the TotalInput float to a string, which worked but the calculator would only allow me to input 7 numbers before showing "Infinite" on the calculator display and then any further input would result in the first number being a "1" despite pressing any of the buttons.

So my question is - how do I do this? All I want is for the string to allow me to place as many numbers as I need on the display. How do I change the text in such a way?


This was done on Visual C++, sorry if that's a problem.


Thanks in advance to anyone who helps.

Help removing duplicates from an array

by nizbit at 13:31 PM, 08/30/2010

I'm trying to find duplicates in an array and removing them by shifting the array index using the same array. I can't figure out where in my code the problem is but I'm still getting a duplicate. Could someone please help pinpoint the problem? I've tried debugging it but I'm not seeing it.
#include <iostream>
using namespace std;

int removeDuplicates(int A[], int n){
        int last = n-1;
        int found = 0;
        //bool flag = false;

        for(int i=0; i < last+1; i++)
        {
                for(int j=i+1; j < last+1; j++)
                {
                        if(A[i] == A[j])
                        {
                                found++;
                                for(int k = j;k < last+1;k++)
                                {
                                        A[k]=A[k+1];
                                        //if(A[k-1] == A[i])
                                        //        flag = true;
                                }
                                last--;
                                j=j+1;
                        }

                }
}
        //found= last-found;
        return last;
}

int main() {

        // Test data
        int n = 24;
        int A[] = {1,1,2,4, 1,1,1,2, 3,5,8,0, 2,-2,-4,1, 9,10,-4,11, 11,8,5,-4};

        // Call
        int last = removeDuplicates(A,n);

        // Print Results
        for(int i = 0; i <= last; i++)
                cout << A[i] << " ";
        cout << endl;

        return 0;
}
Can someone please compile this program and send me the screen shot of the output of this program? I can not compile on the current computer I am on, and all I need is the output screen shot. Thank you so much! It is an analog clock program.

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<stdlib.h>
#include<dos.h>
int main()
{
struct time *t1;     
int gdriver =DETECT,gmode;
initgraph(&gdriver,&gmode,"");
while(1)
{
gettime(t1);
circle(300,150,100);
printf("The current time is: %2d:%02d:%02d.%02d\n", t1->ti_hour,t1->ti_min,t1->ti_sec);
if ( (t1->ti_hour) >12) {t1->ti_hour=t1->ti_hour-12;}
setfillstyle(1,BLUE);
pieslice(300,150,(360-(t1->ti_hour*30))+90,(360-(t1->ti_hour*30))+95,40);
setfillstyle(1,RED);
pieslice(300,150,360-(t1->ti_min *6)+90,360-(t1->ti_min*6)+95,80);
pieslice(300,150,360-(t1->ti_sec *6)+90,360-(t1->ti_sec*6)+91,90);
sleep(1);
}
getch();
closegraph();
return 0;
}

Insert Graphics.

by TheSecOrg at 12:45 PM, 08/30/2010

How can I put graphics into my C++ console app?

Timer in C++

by TheSecOrg at 12:17 PM, 08/30/2010

How can I make a C++ timer?:confused:

C++ PHP library?

by CJX3711 at 12:00 PM, 08/30/2010

I'm trying to send variables from a program in C++ to php for it to process.
Then I want to be able to get the output of the php code.

Is there any way to send variables from C++ to PHP and back?
Maybe using something like POST variables?
I know how to do this in flash, but I was wondering if there is a C++ equivalent.

C++ Timer

by TheSecOrg at 11:56 AM, 08/30/2010

How do I create a Timer in C++?

Segmentation Fault in MySQL Database Class

by DAlexNagy at 10:32 AM, 08/30/2010

I am learning to write C++ code to access data in a MySQL database. My goal is to use a separate class to control the database access so I can use this class elsewhere. To facilitate my learning, I'm working on simple code to connect to a database (success!) and return all rows in a simple and small table (failing!).

The connection is OK through the class constructor but I'm getting a segmentation fault in the 'queryResults = query.store()' in the class method. The backtrace, as I read it, says the failure is in a MySQL routine. (PS: The gtkmm.h is because I eventually want this class to be used by a GUI written in gtkmm.)

Any suggestions would be greatly appreciated!

Dave

[program messages and backtrace of gdb:]
Starting program: /home/dave/Code/mysql/main
[Thread debugging using libthread_db enabled]
main: Trying to instantiate db class...
database: Trying to connect to test...
database: Connection was successful.
main: After instantiation of db class
main: Calling dbselect using:SELECT * FROM SourceType ORDER BY SourceTypeId
database: Do query using SELECT * FROM SourceType ORDER BY SourceTypeId
database: Did 'query << selectsql'

Program received signal SIGSEGV, Segmentation fault.
0x00f15e94 in mysql_send_query () from /usr/lib/libmysqlclient.so.16
(gdb) bt
#0 0x00f15e94 in mysql_send_query () from /usr/lib/libmysqlclient.so.16
#1 0x00f15f30 in mysql_real_query () from /usr/lib/libmysqlclient.so.16
#2 0x00e8445f in mysqlpp::Query::store(char const*, unsigned int) ()
from /usr/lib/libmysqlpp.so.3
#3 0x00e86e05 in mysqlpp::Query::store(mysqlpp::SQLTypeAdapter const&) ()
from /usr/lib/libmysqlpp.so.3
#4 0x0804b2ae in mysqlpp::Query::store (this=0xbffff250)
at /usr/include/mysql++/query.h:467
#5 0x0804a9b7 in DataBase::dbselect (this=0xbffff238, selectsql=...)
at database.cc:31
#6 0x0804c74f in main ()
(gdb)
[end backtrace]

[my main C++ code]
#include <gtkmm.h>
#include <iostream>
#include <mysql++.h>
#include <stdlib.h>
#include "database.h"

using namespace std;
using namespace mysqlpp;

int main() {

//Variables
Glib::ustring SQLstring;
size_t rows = 0;
StoreQueryResult results;

//Connect
cout << "main: Trying to instantiate db class...\n";
DataBase wwdb("test");
cout << "main: After instantiation of db class\n";

//SELECT
SQLstring = "SELECT * FROM SourceType ORDER BY SourceTypeId";
cout << "main: Calling dbselect using:" << SQLstring <<"\n";
if (wwdb.dbselect(SQLstring)) {
cout << "main: Successful!";
rows = wwdb.returnRows();
results = wwdb.returnResults();
cout << "Rows=" << rows << "\n";
for (size_t i = 0; i < rows; i++)
cout << "main: ID: " << results[i]["SourceTypeId"] << " - Name: " << results[i]["SourceTypeName"] << endl;
cout << "main: Select done.\n";
}
else {
cout << "main: FAILED\n";
return -1;
}

[my class header:]

#ifndef DATABASE_H
#define DATABASE_H

#include <gtkmm.h>
#include <stdlib.h>
#include <mysql++.h>

using namespace std;
using namespace mysqlpp;

class DataBase
{
public:
DataBase(Glib::ustring db);
virtual ~DataBase();

bool dbselect(const Glib::ustring&);
size_t returnRows();
StoreQueryResult returnResults();
bool dbinsert(Glib::ustring&);

protected:
Connection conn;
Query query;
StoreQueryResult queryResults;
size_t rows;

};
#endif //DATABASE_H

[my database class methods:]
#include <iostream>
#include <mysql++.h>
#include <stdlib.h>
#include <string>
#include "database.h"

using namespace std;
using namespace mysqlpp;

//Constructor - Connect to DB
DataBase::DataBase(Glib::ustring db) : query(&conn, true) {
cout << "database: Trying to connect to " << db <<"...\n";
conn = new Connection("wwindextest", "localhost", "guest");
if (!conn) {
cout << "FAILED due to: " << conn.error() << "\n";
}
cout << "database: Connection was successful.\n";
query = conn.query();
}

//Destructor - disconnect from DB
DataBase::~DataBase() {
}

//Methods
//SELECT
bool DataBase::dbselect(const Glib::ustring& selectsql) {
cout << "database: Do query using " << selectsql << "\n";
query << selectsql;
cout << "database: Did 'query << selectsql' \n";
if (queryResults = query.store()) {
cout << "Successful! Rows=";
rows = queryResults.num_rows();
cout << rows << "\n";
return true;
}
else {
cout << "FAILED due to " << query.error() << "\n";
return false;
}
}

size_t DataBase::returnRows() {
return rows;
}

StoreQueryResult DataBase::returnResults() {
return queryResults;
}


bool DataBase::dbinsert(Glib::ustring& insertsql)
{
cout << "Do Insert here\n";
return true;
}
/* To insert stuff with escaping */
/*cout << "Trying to insert...\n";
query << "INSERT INTO table " <<
"VALUES (" <<
"\"" << escape << insertData << "\"" <<
");";
query.execute();
cout << "insert done.\n";
*/

[end code]

return 0;
}

C++ & MySQL++ or libgda?

by DAlexNagy at 10:22 AM, 08/30/2010

I am writing a GUI in GKTMM for my own learning experience and to use on a personal project I have at home. The data will be stored in a MySQL database on a server I already have running in my home and which I use for some PHP/JavaScript code that supports a 'library' application I wrote to keep track of the books my wife and I read.

I have a working GUI program but need to tie it into MySQL. Should I use MySQL++ for this or one of the Gnome data access middleware systems (e.g., libgdamm)? What are the advantages of one over the other? I have doc for MySQL++ and am working on a non-GUI program to learn those classes and methods (see another post) and would appreciate if you recommend libgdamm or like middleware, if you could include a link to that doc as well.

BTW, my target system is a Ubuntu 10.04 and I may look to port it to Windows (but that's a ways down the road).

Many Thanks!
Dave

Help. Can't get the loop to stop

by grahf23 at 09:23 AM, 08/30/2010

Hi, i'm new to C++ and been trying to write a simple program to compare the randomly generator number with the number input. But once i got the num1 = num2; the program keep prompting for new input. Any help would be appreciated. Thanks in advance!

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main(){

        char n;
        int amt, num1, num2;
        int count;
        int tries;
       
        srand(time(NULL));

        do
        {
        //code for number generated from 0-99
        for(int i=0; i < 1; ++i){
                num2 = rand() % 100 + 1;        }
        cout<<num2 <<endl;

        loop:
        //amount input
        cout << "Enter the amount $1, $2 or $5: ";
        cin >> amt; // get input
        //setting number of tries
        switch (amt){
        case 1: tries = 2;
        break;
        case 2: tries = 5;
        break;
        case 5: tries = 12;
        break;
        default:
                cout << "Please enter $1, $2 or $5 only..." << endl; goto loop;
               
        }
        //comparing the number
        do
        {
        for (count =0; count < tries ; ++count){

                cout << "Please enter a number: ";
                cin >> num1; // get input
               
                if        (num1 > num2)
               
                        cout << "Entered Number is higher than value, retry with a lower number" << endl;
               
                else if  (num1 < num2)
                       
                        cout << "Entered Number is lower than value, retry with a higher number" << endl;

                else if (num1 == num2)
                {cout << "Congradulations, you have guess the number correctly!!" << endl; break;}
                       
                        }
        }while ( count < tries );
               
                cout << "Sorry, you have exhausted all your tries..." << endl;
        //To exit or continue
        cout << "Enter 'N' or 'n' to exit, any other key to continue..";
        cin >> n;
        n = toupper(n);
        }while (n != 'N');

        return 0;

        }

CGI distribution

by willgr at 08:05 AM, 08/30/2010

Hello, I have built a CGI on Windows Vista. I compiled using Visual C++ Express as follows:

cl /Fescript.cgi /EHsc /O2 script.cpp

I used Dependency Walker to determine what libraries it depends on. It only depends on kernel32.dll

Hypothesis: This CGI should work on any other modern Windows machine by itself i.e. without the need to distribute anything except the CGI itself.

Is that a correct assumption?

figuring out how to use a map

by helpme87 at 07:36 AM, 08/30/2010

so i am trying to write a program that reads some data in from a text file and performs an operation on that data. the text file is as follows...

611111     5
765676    4
876787    4
987897    2
611111    4

now i want the program to read that and see that 611111 is there twice and will add its corresponding values so 611111 will then have a corresponding value of 9. i did some research and found out a map is probably what i need to do this but thats where i am getting confused. im not exactly sure how to read the data into the map from a text file and then how to pick out if there are any similar numbers in the first column.

im not even sure why i am posting what i have so far since i know it is probably embarressingly wrong (especially since i have been working on this for a couple days now). thank you ahead of time!!!

oh and i am using dev-c++ so i cant use strings

char accountNum[6];
int amount;

map<char,int , ltstr> report;

while (!inLN.eof())                     

{           
    inLN.getline(accountNum,6);
    report[accountNum] = amount;
                           
}

error C2143: syntax error : missing ';' before ''template<'

by Freespider at 06:57 AM, 08/30/2010

hey,
i cant understand whats wrong, i guess there is a syntax error
or i didnt include something....


i uploaded only the header file...


thanks...

Attached Files
File Type: h Class_Array.h (419 Bytes)

Codeblocks 10.05

by vinnieashken at 06:51 AM, 08/30/2010

I wanted to make Win32 API applications to get the natural look and feel of the operating system's visual styles.
someone suggested i include
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
in my code but he is using visual studio while am using codeblocks which just ignores the #pragma directive.is there a way to achieve that?? am using codeblocks IDE 10.05

Reading from binary File using fread prints junk message.

by hari.sarvothama at 06:33 AM, 08/30/2010

I'm supposed to write a tcp server program which writes into a file a record as structure.
The code is given below:
int n,i;
 cout<<"Enter number of student records";
 cin>>n;
 for(i=0;i<n;i++)
 {
  cout<<"Enter id,name,average mark";
  cin>>r[i].id>>r[i].name>>r[i].mark;
 }
int i,n1;
 FILE *fp;
 FILE *file = fopen("db.dat", "wb");
 cout<<"Writing into file\n";
 if ( file != NULL )
 {
  for(i=0;i<n;i++)
        fwrite(&r[i], sizeof r[i], 1, file);
  fclose(file);
 }
 cout<<"Writing completed\n";
There is no problem in writing part(or there is????)
When i read from the file using fread it prints junk values. What is the problem??
Does fread not place correct values in respective variables? If not how to do it??
struct rec re;
fread(&re,sizeof re,1,fp);
 for(i=0;i<n;i++)
 {
  fread(&re,sizeof re,1,fp);
  cout<<re.id<<re.name<<re.mark;
 }

How to stop the loop print ????

by myd5258 at 02:34 AM, 08/30/2010

Hi guys;
I wrote a function that inserts a new integer in the ordered link-list. If the number to insert exist in the link-list then the insertion WILL not take place, instead a message “Number To Insert Exists !!” will be produced. Can some1 help me to find out the error that makes the looping print ????


#include <iostream>

using namespace std;

typedef int value;

struct node {
      value num;
      node *next;
      };
     
      typedef struct node *nodePtr;
      void insert(nodePtr &head, value val);
      int getNumber ();
      bool check (nodePtr head, value val);
      void print (nodePtr head);
     
     
int main()
{
    nodePtr head;
    head = NULL;
    value num;
   
    //asssume only postive numbers are inserted
    do {
     
        num = getNumber();
        if (num > 0)
          insert(head, num);
         
        print(head);
        }while (num > 0);
   
    system("pause");
    return 0;
}

int getNumber ()
{
  int num;
  cout<<"Enter Number to be inserted: "<<flush;
  cin>>num;
  return num;
   
}

void insert(nodePtr &head, value val)
{
    nodePtr temp;
    //inserting into an empty list
    if (head == NULL)
    {
             
    temp = new node;
    temp->num = val;
    temp->next = NULL;
        head = temp;
        }
    else
    if (!check(head, val))
    {
          temp = new node;
          temp->num = val;
          temp->next = NULL;
         
          // find location       
              nodePtr findFst = head;
              nodePtr findSec = head;
              while (findFst->next != NULL && findFst->num < val)
              {
                    findSec = findFst;
                    findFst = findFst->next;
                    }
              if (findFst == head) //inserting in begining
              {
                                  temp->next = findFst;
                                  findSec->next = temp;                   
                                  }
              else if (findSec->num < val && findFst->num >val)//inserting in the middle
              {
                    temp->next = findFst;
                    findFst->next = temp;
                    }
              else //insertion at the end
              findFst->next = temp;
          }
    else
          cout<<"Number to be inserted exists"<<endl;
}

bool check (nodePtr head, value val)
{
    while (head != NULL){
          if (head->num == val)
          return true;
          head = head->next;
          }
         
         
          return false;
}


void print (nodePtr head)
{
    while (head != NULL)
    {
          cout<<head->num<<" / ";
          head = head->next;
          }
          cout<<endl;
}
hello all

i'm using cUrl and mysql in PHP but new to c++

for connecting to remote mysql database and run query what i need?
should i install mysql connector? where are mysql libraries?

may i download a large file for example 400 mb in c++ using cUrl ?

i found these example codes :
/*****************************************************************************
 *                                  _  _ ____  _
 *  Project                    ___| | | |  _ \| |
 *                            / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                            \___|\___/|_| \_\_____|
 *
 */
 
#include <stdio.h>
 
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
 
/*
 * This is an example showing how to get a single file from an FTP server.
 * It delays the actual destination file creation until the first write
 * callback so that it won't create an empty file in case the remote file
 * doesn't exist or something else fails.
 */
 
struct FtpFile {
  const char *filename;
  FILE *stream;
};
 
static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
  struct FtpFile *out=(struct FtpFile *)stream;
  if(out && !out->stream) {
    /* open file for writing */
    out->stream=fopen(out->filename, "wb");
    if(!out->stream)
      return -1; /* failure, can't open file to write */
  }
  return fwrite(buffer, size, nmemb, out->stream);
}
 
 
int main(void)
{
  CURL *curl;
  CURLcode res;
  struct FtpFile ftpfile={
    "curl.tar.gz", /* name to store the file as if succesful */
    NULL
  };
 
  curl_global_init(CURL_GLOBAL_DEFAULT);
 
  curl = curl_easy_init();
  if(curl) {
    /*
    * Get curl 7.9.2 from sunet.se's FTP site. curl 7.9.2 is most likely not
    * present there by the time you read this, so you'd better replace the
    * URL with one that works!
    */
    curl_easy_setopt(curl, CURLOPT_URL,
                    "ftp://ftp.sunet.se/pub/www/utilities/curl/curl-7.9.2.tar.gz");
    /* Define our callback to get called when there's data to be written */
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
    /* Set a pointer to our struct to pass to the callback */
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
 
    /* Switch on full protocol/debug output */
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
 
    res = curl_easy_perform(curl);
 
    /* always cleanup */
    curl_easy_cleanup(curl);
 
    if(CURLE_OK != res) {
      /* we failed */
      fprintf(stderr, "curl told us %d\n", res);
    }
  }
 
  if(ftpfile.stream)
    fclose(ftpfile.stream); /* close the local file */
 
  curl_global_cleanup();
 
  return 0;
}
#include <mysql++.h>
#include <stdlib.h>
 
using namespace std;
using namespace mysqlpp;
 
int main() {
    try {
        Connection conn(false);
        conn.connect("DB NAME", "DB HOST probably localhost", "DB USER", "DB PASS");
        Query query = conn.query();
    } catch (BadQuery er) { // handle any connection or
        // query errors that may come up
        cerr << "Error: " << er.what() << endl;
        return -1;
    } catch (const BadConversion& er) {
        // Handle bad conversions
        cerr << "Conversion error: " << er.what() << endl <<
                "\tretrieved data size: " << er.retrieved <<
                ", actual size: " << er.actual_size << endl;
        return -1;
    } catch (const Exception& er) {
        // Catch-all for any other MySQL++ exceptions
        cerr << "Error: " << er.what() << endl;
        return -1;
    }
 
    return (EXIT_SUCCESS);
}

in curl example , how to use it? which function to declare? where to enter url?
how to get download progress and show it?

please help

Can't find the runtime error...

by group256 at 00:44 AM, 08/30/2010

Hi everyone,

I have been playing with a piece of code that is to simulate "shortest job scheduler" for almost 2 days and there is a runtime bug which it's seems I am not able to find. Any help is really appreciated.

Here is the code:

int sjf_scheduler(int number_of_jobs, process_attrib process[])
{
        process_attrib temp;
        vector<int> arrival, time, pid;
       
        cout << "\n\nNow We go to Shortest Job First Algorithm\n";
        cout << "Hit a key....\n";
        cin.get();
        //clscr();

        cout << "==================================================\n"
            << "              Shortest Job First                  \n";

        //Sort and arrange based on arrival time
        for (int i = 0; i < number_of_jobs; i++)
        {
                for (int j = 0; j < number_of_jobs - 1 ; j++)
                {
                        if (process[j].arrival > process[j+1].arrival)
                        {
                                temp = process[j];
                                process[j] = process[j+1];
                                process[j+1] = temp;
                        }

                }
        }

        /* Now copy all the data into 3 vectors to keep the time, arrival,
        * and PID */
        for (int i = 0; i < number_of_jobs; i++)
        {
                arrival.push_back(process[i].arrival);
                time.push_back(process[i].time);
                pid.push_back(process[i].pid);
        }


        int shortest_job;
        int biggest_arrival_time = process[number_of_jobs - 1].arrival;
        int i, index = 0; /* Counter */

        for (int tick = 0; !arrival.empty(); tick++)
        {
                cout << "Tick: " << tick << endl << endl;
                shortest_job = 1000;  /* Set the burst time to a huge value */

                /* We have to get the smallest ARRIVED job */
                cout << "arrival: " << arrival.size() << endl;
                for (i = 0; i < arrival.size(); i++)
                        if (arrival[i] <= tick && shortest_job > time[i])
                        {
                                shortest_job = time[i];
                                index = i;
                        }
                /* When exiting the loop, we have the shortest job by that
                * specific time, now it's time to process it, as it's
                * NON-Preemptive, so it takes the whole CPU time until it's
                * fully finished */
                cout << "Index: " << index << endl;
                if (shortest_job != 1000)
                {
                        cout << "\tProcess " << pid[index] << " finished...\n";
                        tick += shortest_job - 1; /* Time to finish the process */
                        arrival.erase(arrival.begin() + (index - 1)); /* get rid of the process */
                        time.erase(time.begin() + (index - 1)); /* get rid of the process */
                        pid.erase(pid.begin() + (index - 1)); /* get rid of the process */
                }
        }
        cout << "********Done!!*********\n";
}

and here is the error in the console when I say "make":

/**** some parts are deleted here ****/
arrival: 2
Index: 0
        Process 1 finished...
Tick: 63

arrival: 1
Index: 0
        Process 2 finished...
********Done!!*********
*** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x082e20b8 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(+0x6b591)[0x401db591]
/lib/tls/i686/cmov/libc.so.6(+0x6c80e)[0x401dc80e]
/usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0x400ef741]
./a.out[0x804c171]
./a.out[0x804be6f]
./a.out[0x804b7f6]
./a.out[0x804b13b]
./a.out[0x804a4fe]
./a.out[0x8048f52]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0x40186bd6]
./a.out[0x8048de1]
======= Memory map: ========
08048000-0804e000 r-xp 00000000 08:01 396319    /home/sam/OS/a.out
0804e000-0804f000 r--p 00005000 08:01 396319    /home/sam/OS/a.out
0804f000-08050000 rw-p 00006000 08:01 396319    /home/sam/OS/a.out
082e2000-08303000 rw-p 00000000 00:00 0          [heap]
40000000-4001b000 r-xp 00000000 08:01 3676549    /lib/ld-2.11.1.so
4001b000-4001c000 r--p 0001a000 08:01 3676549    /lib/ld-2.11.1.so
4001c000-4001d000 rw-p 0001b000 08:01 3676549    /lib/ld-2.11.1.so
4001d000-4001e000 r-xp 00000000 00:00 0          [vdso]
4001e000-40022000 rw-p 00000000 00:00 0
40034000-4011d000 r-xp 00000000 08:01 7081651    /usr/lib/libstdc++.so.6.0.13
4011d000-4011e000 ---p 000e9000 08:01 7081651    /usr/lib/libstdc++.so.6.0.13
4011e000-40122000 r--p 000e9000 08:01 7081651    /usr/lib/libstdc++.so.6.0.13
40122000-40123000 rw-p 000ed000 08:01 7081651    /usr/lib/libstdc++.so.6.0.13
40123000-4012a000 rw-p 00000000 00:00 0
4012a000-4014e000 r-xp 00000000 08:01 3676439    /lib/tls/i686/cmov/libm-2.11.1.so
4014e000-4014f000 r--p 00023000 08:01 3676439    /lib/tls/i686/cmov/libm-2.11.1.so
4014f000-40150000 rw-p 00024000 08:01 3676439    /lib/tls/i686/cmov/libm-2.11.1.so
40150000-40151000 rw-p 00000000 00:00 0
40151000-4016e000 r-xp 00000000 08:01 3672391    /lib/libgcc_s.so.1
4016e000-4016f000 r--p 0001c000 08:01 3672391    /lib/libgcc_s.so.1
4016f000-40170000 rw-p 0001d000 08:01 3672391    /lib/libgcc_s.so.1
40170000-402c3000 r-xp 00000000 08:01 3676435    /lib/tls/i686/cmov/libc-2.11.1.so
402c3000-402c4000 ---p 00153000 08:01 3676435    /lib/tls/i686/cmov/libc-2.11.1.so
402c4000-402c6000 r--p 00153000 08:01 3676435    /lib/tls/i686/cmov/libc-2.11.1.so
402c6000-402c7000 rw-p 00155000 08:01 3676435    /lib/tls/i686/cmov/libc-2.11.1.so
402c7000-402cb000 rw-p 00000000 00:00 0
bff41000-bff56000 rw-p 00000000 00:00 0          [stack]
make: *** [make] Aborted

Thank you.

Pass variable from C++ to environment on Linux

by 333kyle333 at 20:34 PM, 08/29/2010

I asked this before, but I have to ask again considering I still haven't found a way to do this. I need to know if there's a way to take a variable inputted into a C++ program and pass it to the terminal as an environment variable. Again, I'm running Ubuntu if it matters.

accept only one character from user

by silvertooth07 at 19:34 PM, 08/29/2010

i'm having a problem on the program we're tasked to do.

originally, the "option" is an int but someone suggested to make it a character. i thought the problem was solved (i want to make the program print: "invalid output" if the user inputted non-numerical values) but when i tried to enter 11, 12, etc. it didn't go to the default part. i understand that even if you enter many characters, only one character will be read. the problem is how can allow my program to enter only one character? also, is it possible that after the user inputted a number, it function will be executed? (i mean, i don't have to enter, it will just execute automatically.)

thanks!


here's a piece of the program:

int main()

    start_ptr = NULL;
    do
        {
          cout << endl;
          cout << "Please select an option : " << endl;
          cout << "1. Add a node at the start of the list." << endl;
          cout << "2. Add a node to the end of the list." << endl;
          cout << "3. Delete the start node from the list." << endl;
          cout << "4. Delete the end node from the list." << endl;
          cout << "5. Move the current pointer on one node." << endl;
      cout << "6. Move the current pointer back one node." << endl;
      cout << "7. Exit the program." << endl;

      cout << endl << " --->>> ";
          cin >> option;
         
          switch (option)
            {
          case '1' : add_start(); break;
              case '2' : add(); break;
              case '3' : delete_start(); break;
              case '4' : delete_end(); break;
              case '5' : move_current_on(); break;
          case '6' : move_current_back();break;
          case '7':
              {  information();
                  system("pause>null");
                  exit();
                  break;
              }
          default: cout<<"INVALID INPUT!!";
            }
            if (option <= '7')
          display();
        }
    while (option != '7');
}

how to run a C++ program after its been compiled

by spamwich56 at 16:13 PM, 08/29/2010

Hi!

This will probably be an easy question to answer but the solution is eluding me. I just started writing c++ programs and they work fine on my computer (I use visual studio to compile them). the problem I am having is I would run my program on another computer and I simply cant figure out how to do that without taking the source code and re-compiling it on the second computer.

Is there a way to make an .exe file or something similar that I can just put on the other computer and have it run?? Any help would be very greatly appreciated.

A Basketball League Schedule-Maker?

by jonsan32 at 16:10 PM, 08/29/2010

ANY advice would help. Even if you just say "It's im/possible"

I have a basketball league with 500 teams to schedule every year, and would love a program that would alleviate that 2-week headache. If you know of any programs that can do this, or if you are willing/able to construct a program that can do this, or if you have any advice on how I can do this myself, please let me know.

For a visual and interactive explanation, I've constructed the following so you can understand EXACTLY what I'm looking for:


What I want the program to look like: http://dl.dropbox.com/u/5739741/jamsched.txt (the html can be viewed at http://htmledit.squarefree.com or an html editor of your choice.

And here's the schedule I would like the program to populate: https://spreadsheets.google.com/pub?...en&output=html


If you or someone you know can do this, we are willing to pay. Thanks for your time.

Simple Do... While Problem

by ichigo_cool at 15:36 PM, 08/29/2010

I'm working on a program to save and load character files for a text-based RPG.
There are three slots to save to. I'm having the user enter whichever slot he wants to save to through inputting an integer. If the number is lower than 1 or higher than 3 I want the program to go back to the beginning, hence the do...while loop. However, it doesn't recognize overwriteSlot because it's local to the scope, and when I put it in the main loop the while section won't recognize the change in overwriteSlot, since it's happening locally. How can I make it so that it'll work. If the user enters 4, then have the whole thing restart. Thanks for any help!

int overwriteSlot;

do        {
                cout << "Which slot would you like to overwrite >> ";
                cin >> overwriteSlot;
                cin.ignore();

                if (overwriteSlot <= 3) cout << "Save complete in slot " << overwriteSlot << "." << endl;
                else cout << "There is no such slot!" << endl;
        }
        while (overwriteSlot < 1 && overwriteSlot > 3);

Problems with unique()

by therobot at 15:22 PM, 08/29/2010

I'm having problems with unique().

I have some code that goes something like this:

std::map<int, CompCont> sysRelMap;

for each(pair<int, CompCont> comp in sysRelMap)
{
        list<pair<string,string>>::iterator newEnd =
                unique(comp.second.connList.begin(), comp.second.connList.end(), equalPair);
        comp.second.connList.erase(newEnd,comp.second.connList.end());
}

equalPair is a small, simple function:

bool ScriptWriter::equalPair(const pair<string, string> first, const pair<string, string> second)
{
        return (first.first.compare(second.first) == 0) && (first.second.compare(second.second) == 0);
}

CompCont is a class I created that contains, for this example, one important data member, a list< pair<string,string> > connList. When I set a breakpoint at the end of each for loop, it lists comp.second.connList correctly (with only unique pairs) but as soon as it breaks out of that for loop sysRelMap goes back to having the values of each CompCont.connList to what it was before unique() and erase() were called. Hopefully this is understandable.

I'm assuming it's somehow that my functions are being passed copies of the list objects instead of references to them, but am not sure how I would modify my code to handle. I just followed many of the examples online for how to do this with the Binary Predicate function, and they all looked similar to what I have. I didn't see anything about passing references, etc, but they also weren't dealing with lists encapsulated in other objects.

I thought this might work:
for each(pair<int, CompCont> comp in sysRelMap)
{
        list<pair<string,string>> modList = comp.second.connList;
        list<pair<string,string>>::iterator newEnd =
                unique(modList.begin(), modList.end(), equalPair);
        modList.erase(newEnd,modList.end());
        comp.second.connList = modList;
}

.. but it didn't. Still, afterwards, the list objects in each CompCont in the sysRelMap remain the same as they were before the for each loop.

Any input would be greatly appreciated. Feel like I'm missing something small, and that's bugging me.

need help with an easy project

by jelinky at 15:09 PM, 08/29/2010

My program reads water temperatures from a river as well as when the temps were recorded from an input file called "biodata.dat." Then the data is outputted in a file called "results.dat" (i havent added this results.dat part in my code but do know how to do it)
The input file looks like this:
2 // number of readings
200707211245 F70.5 // timestamp recored plus temp in Fahrenheit
200708220812 C19.97 // same but in Celsius

I am supposed to arrange the data so that the times and temperature readings(all temp readings must be in Celsius by formula) make sense, like this:
21.38C recorded on 07/21/2007 at 12:45
19.97C recorded on 08/22/2007 at 8:12.

my problem is that i dont know how to make the program only change the fahrenheit temperatures and not the celsius temperatures. how can i write something to tell them apart and use a formula to change specific temps?

btw, the formula from fahrenheit to celsius is C = 5 / 9 (F - 32)

this is the code i have so far:

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

int main() {
       
        int numone;
        double degrees;
        string timestamp,
                  temp;
                 
        ifstream infile;
        infile.open("biodata.dat");
        if (!infile)
        {
                        cout << "Error opening biodata.dat\n";
                        system("pause");
        }
       

       
        infile >> numone;
        cout << "Number of recordings: "<<numone<<"\n\n";
       
        for (int i=1; i <= (numone); i++)
{
   
    cout<<i<<":  ";
       
       
                  infile >> timestamp;

                  string year = timestamp.substr(0,4);
                  string month = timestamp.substr(4,2);
                  string date = timestamp.substr(6,2);
                  string hour = timestamp.substr(8,2);
                  string minute = timestamp.substr(10,2);
                  cout << month << "/" << date << "/" << year << " "
                          << hour  << ":" << minute << "    Temp: ";
                 
                  infile >> temp; // F to C: (F - 32)(5/9)
                 
                  string unit = temp.substr(0,1);
                  string strtemp = temp.substr(1,temp.length());
                  double atof(char* strtemp);
                 
                  cout<<strtemp.c_str();
                  cout<<"\n";
                 
                 
}

cout<<"\n\n";       
system("pause");
return 0; 
}

heres the .dat (text) file:
2
200707211245 F70.5
200708220812 C19.97
2008 scandalz.net
Horses are forbidden to eat fire hydrants in Marshalltown, Iowa.
CountryUS
IP Address38.107.191.92
User AgentCCBot/1.0 (+http://www.commoncrawl.org/bot.html)