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.

Move Constructor

by kim00000 at 13:46 PM, 05/19/2012

Hello Daniwebers!

I was just reading This C++0x Beginner Tutorial: http://www.daniweb.com/software-development/cpp/tutorials/373787/beginning-c0x-making-a-raii-class

And I was confused by something:

"
int_vector(int_vector& aV);

Obviously, this type of constructor would allow the transfer of the resource, since the source object can be modified and put into an empty-state (or "zombie-state"). But there are two problems with the above, which make it an impractical solution. First, a temporary object, formally referred to as anrvalue, cannot be bound to a non-const reference, meaning that this constructor will not be able to move resources from a temporary object to the newly constructed object."

I have a question here: Isn't the compiler-generated copy constructor called if I used an rvalue like int_vector(int_vector(5)) and it gets a shallow copy of the temporary object just like the move constructor?

Thanks in advance,
Kimo

Help C++ Classes

by jeav12 at 08:18 AM, 05/19/2012

Why does this program doesn't work ?

AVIStreamGetFrameOpen Problem

by tomtetlaw at 01:11 AM, 05/19/2012

First of all I learnt how to do this from http://nehe.gamedev.net/tutorial/playing_avi_files_in_opengl/23001/

AVIStreamGetFrameOpen is always returning NULL. I checked to see if I could open the AVI file in windows media player and that worked, so that means it can't be a codec problem, right? I'm not too sure. All the variables have valid values before the call to AVIStreamGetFrameOpen

Here's my code:

if (AVIStreamOpenFromFile(&avi, file, streamtypeVIDEO, 0, OF_READ, NULL) != 0)
    return;

AVIStreamInfo (avi, &info, sizeof(info));
w = info.rcFrame.right - info.rcFrame.left;
h = info.rcFrame.bottom - info.rcFrame.top;
lastframe = AVIStreamLength (avi);
mpf = AVIStreamSampleToTime (avi, lastframe) / lastframe;

header.biSize = sizeof (BITMAPINFOHEADER);                  
header.biPlanes = 1;                                        
header.biBitCount = 24;                                     
header.biWidth = w;                                     
header.biHeight = h;                                        
header.biCompression = BI_RGB;                              

bitmap = CreateDIBSection (hdc, (BITMAPINFO*)(&header), DIB_RGB_COLORS, (void**)(&data), NULL, NULL);
SelectObject (hdc, bitmap);

pgf = AVIStreamGetFrameOpen (avi, NULL);
if (!pgf)
    return;

tile map not working

by hwoarang69 at 00:56 AM, 05/19/2012

for some reason iam not getting the right map. i think the problem is

x += 130;
y += 130;





#include "DarkGDK.h"

const int ROWS = 10;
const int COLS = 13;
int level[ROWS][COLS] =    {
    {1,1,1,1,1,1,1,1,1,1,1,1,1},
    {1,0,0,0,0,0,0,0,0,0,0,0,1},
    {1,0,0,0,0,0,0,0,0,0,0,0,1},
    {1,0,0,0,0,0,0,0,0,0,0,0,1},
    {1,0,0,0,0,0,0,0,0,0,0,0,1},
    {1,0,0,0,0,0,0,0,0,0,0,0,1},
    {1,0,0,0,0,0,0,0,0,0,0,0,1},
    {1,0,0,0,0,1,1,0,0,0,0,0,1},
    {1,0,0,0,0,1,1,0,0,0,0,0,1},
    {1,1,1,1,1,1,1,1,1,1,1,1,1}
};

void DarkGDK(void)
{
    dbSyncOn();
    dbSyncRate(60);
    dbDisableEscapeKey();

    dbLoadImage("rock.bmp", 1);


        int x = 0; 
        int y = 0;
        for(int r = 0; r < ROWS; r++)
        {
            x = 0;
            for(int c = 0; c < COLS; c++)
            {
                dbPasteImage(level[r][c], x, y);
                x += 130;
            }
            y += 130;
        }


    while(LoopGDK())
    {
        if(dbEscapeKey() == 1)
        {
            break;
        }

        dbSync();
    }
}

Same datatype cause Runtime terminate in an unusual way

by blueyan at 00:15 AM, 05/19/2012

Click Here for the snapshot of my problem.

    string operand;
    string opCode;

   struct MacroNameTable{
       string macroName;
       int start;
       int end;
       int invocation; 
       string operandCounter;      
       };

struct MacroNameTable NAMTAB[NAMSize];  

      void addNAMTab(){
            NAMcounter++;
            cout <<"check NAMcounter: ["<<NAMcounter<<"]"<<endl;//debug
            cout <<"check this operand: ["<<operand<<"]"<<endl;//debug
            cout <<"check this opCode: ["<<opCode<<"]"<<endl;//debug

            NAMTAB[NAMcounter].macroName=opCode;
            NAMTAB[NAMcounter].start=DEFcounter;
            NAMTAB[NAMcounter].operandCounter="AA";
        }

operand and opCode will read from text file. As you can see from the snapshot, after read from file,
current operand="&INDEV, &BUFADR, &RECLTH"
current opCode="RDBUFF"

this line cause a problem , it gives me runTime error

NAMTAB[NAMcounter].macroName=opCode;

but if i change to

 NAMTAB[NAMcounter].macroName=operand;

then it is working again. Click Here

why ?? I've debug whole day long and I still cannot solve this, it supposed to be working because opCode is string , so does NAMTAB[NAMcounter].macroName

dark gdk jumping

by hwoarang69 at 20:08 PM, 05/18/2012

hi, i just started learing 2d game programming. so far i can make my character go right, left and check for collisions. But i cant find out how to make him jump. any thing will be helpfull.

i now i will have something like

while (LoopGDK())
if(dbUpKey() == 1)
{
..
}
}

dark gdk collision

by hwoarang69 at 15:25 PM, 05/18/2012

so this program is really simply. my player(ch1,bmp) just move right and left. on my map there are wall and coin. if player hit a wall it should stop. but if it hit a coin, coin should get delete.

problem iam having is that for some reason player(ch.bmp) is display as a coin.
i think its bc iam not using sprite right.

#include "DarkGDK.h"

void DarkGDK (void)
{
    dbSyncOn();           // dbSyncOn() =  turn sync on, this means we control when the screen is updated
    dbSyncRate(60);       //maximum frame rate will be set at 60 frames per second
    dbDisableEscapeKey(); // to exit from main while loop and stop the game


    dbSetImageColorKey(255,255,255); //igore color

    dbLoadImage("ch1.bmp",1);       //load image to memory
    dbLoadImage("wall.bmp",2);
    dbLoadImage("coin.bmp",3);

    dbSprite(1,100,50,1);          //mage#,x,y,image# -display image
    dbSprite(1,400,50,2);
    dbSprite(1,250,50,3);

    // keep looping through until user enter escape key
    while (LoopGDK())
    {
        //move image forward
        if(dbRightKey() == 1)
        {
            dbRotateSprite(1, 90); //rotate image
            dbMoveSprite(1,1);    //image#, move one space up
            dbRotateSprite(1,0);  //rotate back to normal
            if(dbSpriteCollision(1,3) == 1) //del coin
            {
                dbDeleteSprite(3);
            }
            if(dbSpriteCollision(1, 2) == 1)
            {
                dbRotateSprite(1, 270); //rotate image
                dbMoveSprite(1,1);    //image#, move one space up
                dbRotateSprite(1,0);  //rotate back to normal
            }
        }
        //move image left
        if(dbLeftKey() == 1)
        {
            dbRotateSprite(1, 270); //roate image
            dbMoveSprite(1,1); //image#, move one space up
            dbRotateSprite(1,0); //rotate back to normal
            if(dbSpriteCollision(1,3) == 1)  //del coin
            {
                dbDeleteSprite(3);
            }
            if(dbSpriteCollision(1, 2) == 1)
            {
                dbRotateSprite(1, 90); //rotate image
            dbMoveSprite(1,1);    //image#, move one space up
            dbRotateSprite(1,0);  //rotate back to normal
            }
        }

        if (dbEscapeKey() == 1) //if the ecape key is pressed, the program will exit
        {
            break;
        }
        dbSync(); //update the screen

    }//end of main while loop


    for(int i = 1; i < 10; i++)
    {
        dbDeleteImage(i);   //delete 
        dbDeleteSprite(i);  //delete
    }
    return;
}

PDB file error in Visual Studio 2010 express

by MasterHacker110 at 13:14 PM, 05/18/2012

When i compile my code with visual studio 2010 express i get the following errors:

'Client.exe': Unloaded 'C:\Windows\SysWOW64\WSHTCPIP.DLL'

And with the other program i get these:

'Server.exe': Loaded 'C:\Users\User\Desktop\Server\Debug\Server.exe', Symbols loaded.
'Server.exe': Loaded 'C:\Windows\SysWOW64\ntdll.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\kernel32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\KernelBase.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\ws2_32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\msvcrt.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\rpcrt4.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\sspicli.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\cryptbase.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\sechost.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\nsi.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\msvcr100d.dll', Symbols loaded.
'Server.exe': Loaded 'C:\Windows\SysWOW64\mswsock.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\user32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\gdi32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\lpk.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\usp10.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\advapi32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\imm32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\msctf.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Program Files (x86)\Searchqu Toolbar\Datamngr\datamngr.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\wtsapi32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\dbghelp.dll', Cannot find or open the PDB file
'Server.exe': Unloaded 'C:\Program Files (x86)\Searchqu Toolbar\Datamngr\datamngr.dll'
'Server.exe': Unloaded 'C:\Windows\SysWOW64\dbghelp.dll'
'Server.exe': Unloaded 'C:\Windows\SysWOW64\wtsapi32.dll'
'Server.exe': Loaded 'C:\Program Files (x86)\Searchqu Toolbar\Datamngr\IEBHO.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\dbghelp.dll', Cannot find or open the PDB file
'Server.exe': Unloaded 'C:\Program Files (x86)\Searchqu Toolbar\Datamngr\IEBHO.dll'
'Server.exe': Unloaded 'C:\Windows\SysWOW64\dbghelp.dll'
'Server.exe': Loaded 'C:\Windows\SysWOW64\WSHTCPIP.DLL', Cannot find or open the PDB file
'Server.exe': Unloaded 'C:\Windows\SysWOW64\WSHTCPIP.DLL'

What is worng and how can i fix this.

Thanks...

Help with GUI

by hekri at 12:15 PM, 05/18/2012

Hi,
I've just finished my c++ class (mechanical engineering) and as the final exam we have to create a simple program with graphical user interface and I need some help from you guys.

The task is this: we have to make a simple GUI that can take the diameters of a Shaft/Hole and calculate how they fit together (pressed, smooth fit...).

Now the problem: i could write the code in c++ but i don't know how to create the buttons or the user interface and how to connect the code with those buttons.

I'm using Visual Studio 2010 professional.

P.S Don't get me wrong i'm not asking you to do my work, just some suggestions on where to start or maybe some tutorials or something like that.
Thank you.

P.S If this is the wrong place for this thread feel free to move it or tell me i' ll remove it.

Thanks.

Lil' problem to convert string to int

by mohur at 11:12 AM, 05/18/2012

Hello, im a bit new to c++ and learning in my own, but im stuck to a problem.
Im trying to do a practice converting string/c-string to int :

Sum of Digits in a String
Write a program that asks the user to enter a series of single digit numbers with nothing
separating them. Read the input as a C-string or a string object. The program
should display the sum of all the single-digit numbers in the string. For example, if the
user enters 2514, the program should display 12, which is the sum of 2, 5, 1, and 4.

so i make a simple program first like this :

#include <iostream>
#include <cstdlib>


using namespace std;

int main()
{
    const int size = 5;
    char array[size];
    int acc = 0;//for accumulator

    int number[5];

    for(int count = 0; count < size; count++)
    {
        cout<<"enter a number = ";
        cin>>array[count];
        number[count] = atoi(array[count]);
        acc += 0;

    }

    cout<<endl<<"the total number = "<<acc;


    return 0;
}

but theres problem in 'atoi' to convert the string, the compiler says = 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
anyone can help me?

windows form choppy movement

by jonnyboy12 at 10:20 AM, 05/18/2012

Hello. I am working on a windows form right now. My form is very full and i am using many textures. I have double buffered my form and made exteded classes for anything with a texture that has double buffering. Before i had double buffered everything my form was very jerky when i moved it offscreen. It would kinda stick and jerk. I notice this happens only when i move it offscreen. I have not found any information on this anywhere, im surprized im the only one who has experiences this. Another thing i have thaught of is drawing and offscreen image of my form, but i do not know how to do that . Thans all for any advice i cant continue on my project until this has been resolved thanks.

#include<GL/glut.h>
#include<Math.h>
#include<iostream>
using namespace std;
int direction=0;
void drawRectangle(GLfloat x1,GLfloat y1,GLfloat x2,GLfloat y2)
{
    glBegin(GL_LINES);
    glVertex2f(x1,y1);
    glVertex2f(x1,y2);
    glVertex2f(x1,y1);
    glVertex2f(x2,y1);
    glVertex2f(x2,y1);
    glVertex2f(x2,y2);
    glVertex2f(x1,y2);
    glVertex2f(x2,y2);
    glEnd();
}
void drawQuadrants()
{
    glLoadIdentity();
    glBegin(GL_LINES);
    glVertex2f(0.0,-1.0);
    glVertex2f(0.0,1.0);
    glVertex2f(-1.0,0.0);
    glVertex2f(1.0,0.0);
    glEnd();
}
void display()
{
    glPushMatrix();
    glLoadIdentity();
    glClearColor(0.0f,0.0f,0.0f,0.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glDisable(GL_DEPTH_TEST);
    glColor3f(1.0f,1.0f,1.0f);
    drawQuadrants();
    glPopMatrix();
    if(direction==1)
    {
    glTranslatef(0.2*(1.0-cos(-1.0))+0.3*sin(-1.0),0.3*(1.0-cos(-1.0))-0.2*sin(-1.0),0.0f);
    glRotatef(-1,0.2,0.3,1);
    cout<<0.3*(1.0-cos(-1.0))-0.2*sin(-1.0)<<"\n";
    }
    else if(direction==2)
    {
    glTranslatef(0.2*(1.0-cos(1.0))+0.3*sin(1.0),0.3*(1.0-cos(1))-0.2*sin(1.0),0.0f);
    glRotatef(1,0.2,0.3,1);
    cout<<0.3*(1.0-cos(1))-0.2*sin(1.0)<<"\n";
    }
    drawRectangle(0.2,0.3,0.3,0.4);
    direction=0;
    glFlush();
}
void nkeyboard(unsigned char key,int x,int y)
{
    if(key==27)
        exit(0);
    else if(key=='l'|| key=='L')
        direction=1;
    else if(key=='r' || key=='R')
        direction=2;
    else
        direction=0;
    glutPostRedisplay();
}
int main(int argc,char **argv)
{
    glutInit(&argc,argv);
    glutInitWindowSize(900,900);
    glutInitWindowPosition(100,100);
    glutCreateWindow("Rotation animation");
    glutDisplayFunc(display);
    glutKeyboardFunc(nkeyboard);
    glutMainLoop();
    return 0;
}

Issue in OpenDialog

by anjali.dhasmana at 09:43 AM, 05/18/2012

In my project (Borland C++ Builder, Windows Xp ) am using following code for opening the file

  TOpenDialog *OpenDialog;

   OpenDialog->Filter = "all files (*.*)";
     OpenDialog->InitialDir="::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
     OpenDialog->Execute();

But the "My computer" tab is empty its not showing the drives. Rest "My Rescent Documnets" , "Desktop", "My Documents", "My network drives" all are showing the folders or drives in them.

I had created a new project in BCB with the same above code in that its working fine. When i am including this new project files in my old project again the error is reproducable.

I tried to use OpenFileDialog the code as follows :-

   OpenFileDialog *OpenFileDialog1 = new OpenFileDialog;

   OpenFileDialog1->Filter = "all files (*.*)";
     OpenFileDialog1->InitialDir="::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
     OpenFileDialog1->Execute();

this is giving compliation error : Undefined symbol 'OpenFileDialog'
Help me out to figure out the problem

AVI Player

by tomtetlaw at 08:45 AM, 05/18/2012

Are there any libraries out there that allow me to play .avi files within my OpenGL application?

Need help with c++ network client.

by MasterHacker110 at 08:03 AM, 05/18/2012

I have this C++ network client program but it has an error.

Here is the error:
error C2664: 'wsprintfW' : cannot convert parameter 1 from 'char [128]' to 'LPWSTR'

Here is the code:

// Client program example
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define DEFAULT_PORT 2007
// TCP socket type
#define DEFAULT_PROTO SOCK_STREAM 

void Usage(char *progname)
{
fprintf(stderr,"Usage: %s -p [protocol] -n [server name/IP] -e [port_num] -l [iterations]\n", progname);
fprintf(stderr,"Where:\n\tprotocol is one of TCP or UDP\n");
fprintf(stderr,"\t- server is the IP address or name of server\n");
fprintf(stderr,"\t- port_num is the port to listen on\n");
fprintf(stderr,"\t- iterations is the number of loops to execute.\n");
fprintf(stderr,"\t- (-l by itself makes client run in an infinite loop,\n");
fprintf(stderr,"\t- Hit Ctrl-C to terminate it)\n");
fprintf(stderr,"\t- The defaults are TCP , localhost and 2007\n");
WSACleanup();
exit(1);
}

int main(int argc, char **argv)
{
char Buffer[128];
// default to localhost
char *server_name= "localhost";
unsigned short port = DEFAULT_PORT;
int retval, loopflag = 0;
int i, loopcount, maxloop=-1;
unsigned int addr;
int socket_type = DEFAULT_PROTO;
struct sockaddr_in server;
struct hostent *hp;
WSADATA wsaData;
SOCKET  conn_socket;

if (argc >1)
   {
    for(i=1; i<argc; i++)
    {
        if ((argv[i][0] == '-') || (argv[i][0] == '/'))
       {
            switch(tolower(argv[i][1]))
             {
                case 'p':
                    if (!stricmp(argv[i+1], "TCP"))
                        socket_type = SOCK_STREAM;
                    else if (!stricmp(argv[i+1], "UDP"))
                       socket_type = SOCK_DGRAM;
                    else
                       Usage(argv[0]);
                    i++;
                    break;
                case 'n':
                    server_name = argv[++i];
                    break;
                case 'e':
                    port = atoi(argv[++i]);
                    break;
                case 'l':
                   loopflag =1;
                    if (argv[i+1]) {
                        if (argv[i+1][0] != '-') 
                            maxloop = atoi(argv[i+1]);
                    }
                   else
                       maxloop = -1;
                    i++;
                    break;
                default:
                    Usage(argv[0]);
                    break;
            }
        }
        else
            Usage(argv[0]);
    }
}

if ((retval = WSAStartup(0x202, &wsaData)) != 0)
{
  fprintf(stderr,"Client: WSAStartup() failed with error %d\n", retval);
    WSACleanup();
   return -1;
}
else
   printf("Client: WSAStartup() is OK.\n");

if (port == 0)
{
    Usage(argv[0]);
}

// Attempt to detect if we should call gethostbyname() or gethostbyaddr()
if (isalpha(server_name[0]))
{   // server address is a name
    hp = gethostbyname(server_name);
}
else
{ // Convert nnn.nnn address to a usable one
    addr = inet_addr(server_name);
    hp = gethostbyaddr((char *)&addr, 4, AF_INET);
}
if (hp == NULL )
{
    fprintf(stderr,"Client: Cannot resolve address \"%s\": Error %d\n", server_name, WSAGetLastError());
    WSACleanup();
   exit(1);
}
else
   printf("Client: gethostbyaddr() is OK.\n");
// Copy the resolved information into the sockaddr_in structure
memset(&server, 0, sizeof(server));
memcpy(&(server.sin_addr), hp->h_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = htons(port);
conn_socket = socket(AF_INET, socket_type, 0); /* Open a socket */

if (conn_socket <0 )
{
    fprintf(stderr,"Client: Error Opening socket: Error %d\n", WSAGetLastError());
    WSACleanup();
    return -1;
}
else
   printf("Client: socket() is OK.\n");
// Notice that nothing in this code is specific to whether we 
// are using UDP or TCP.
// We achieve this by using a simple trick.
//    When connect() is called on a datagram socket, it does not 
//    actually establish the connection as a stream (TCP) socket
//    would. Instead, TCP/IP establishes the remote half of the
//    (LocalIPAddress, LocalPort, RemoteIP, RemotePort) mapping.
//    This enables us to use send() and recv() on datagram sockets,
//    instead of recvfrom() and sendto()

printf("Client: Client connecting to: %s.\n", hp->h_name);
if (connect(conn_socket, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
    fprintf(stderr,"Client: connect() failed: %d\n", WSAGetLastError());
    WSACleanup();
   return -1;
}
else
   printf("Client: connect() is OK.\n");
// Test sending some string
loopcount = 0;
while(1)
{
    wsprintf(Buffer,"This is a test message from client #%d", loopcount++);
    retval = send(conn_socket, Buffer, sizeof(Buffer), 0);
    if (retval == SOCKET_ERROR)
    {
        fprintf(stderr,"Client: send() failed: error %d.\n", WSAGetLastError());
        WSACleanup();
        return -1;
    }
    else
     printf("Client: send() is OK.\n");
     printf("Client: Sent data \"%s\"\n", Buffer);

          retval = recv(conn_socket, Buffer, sizeof(Buffer), 0);
    if (retval == SOCKET_ERROR)
   {
        fprintf(stderr,"Client: recv() failed: error %d.\n", WSAGetLastError());
        closesocket(conn_socket);
        WSACleanup();
        return -1;
    }
    else
        printf("Client: recv() is OK.\n");

    // We are not likely to see this with UDP, since there is no
    // 'connection' established.
    if (retval == 0)
   {
        printf("Client: Server closed connection.\n");
        closesocket(conn_socket);
        WSACleanup();
        return -1;
    }


    printf("Client: Received %d bytes, data \"%s\" from server.\n", retval, Buffer);
    if (!loopflag)
   {
        printf("Client: Terminating connection...\n");
        break;
    }
    else
   {
        if ((loopcount >= maxloop) && (maxloop >0))
        break;
    }
}
closesocket(conn_socket);
WSACleanup();

return 0;

}

How do i fix this error??

Thanks...

WINAPI simple window problem

by cool_zephyr at 07:34 AM, 05/18/2012

hello everyone..i'm trying to create a simple window using Win API in visual studio 2010 using the code below

#include <Windows.h>

LPCTSTR  g_lptstrClassName="myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
    switch(msg)
    {
    case WM_CLOSE:
        DestroyWindow(hwnd);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd,msg,wParam,lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG msg;

    wc.cbSize=sizeof(WNDCLASSEX);
    wc.style=0;
    wc.lpfnWndProc=WndProc;
    wc.cbClsExtra=0;
    wc.cbWndExtra=0;
    wc.hInstance=hInstance;
    wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
    wc.hCursor=LoadCursor(NULL,IDC_ARROW);
    wc.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName=NULL;
    wc.lpszClassName=g_lptstrClassName;
    wc.hIconSm=LoadIcon(NULL,IDI_APPLICATION);

    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL,"Registration Failed!!","Error!",MB_ICONEXCLAMATION|MB_OK);
        return 0;
    }

    MessageBox(NULL,"Registration successful!!!","OK",MB_OK);

    hwnd=CreateWindowEx(WS_EX_CLIENTEDGE,g_lptstrClassName,"TITLE",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,
        240,120,NULL,NULL,hInstance,NULL);

    if(hwnd==NULL)
    {
        MessageBox(NULL,"Window Creation Failed!","Error",MB_ICONEXCLAMATION|MB_OK);
        return 0;
    }

    ShowWindow(hwnd,nCmdShow);
    UpdateWindow(hwnd);

    while(GetMessage(&msg,NULL,0,0)>0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}

but when i try the following code..i get the following 7 errors

Error 1 error C2146: syntax error : missing ';' before identifier 'PVOID64' c:\program files\microsoft sdks\windows\v5.0\include\winnt.h 222 1 winapi_1

Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\program files\microsoft sdks\windows\v5.0\include\winnt.h 222 1 winapi_1

Error 3 error C2146: syntax error : missing ';' before identifier 'Buffer' c:\program files\microsoft sdks\windows\v5.0\include\winnt.h 5940 1 winapi_1

Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\program files\microsoft sdks\windows\v5.0\include\winnt.h 5940 1 winapi_1

Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\program files\microsoft sdks\windows\v5.0\include\winnt.h 5940 1 winapi_1

6   IntelliSense: expected a ';'    c:\program files\microsoft sdks\windows\v5.0\include\winnt.h    222 27  

7   IntelliSense: identifier "PVOID64" is undefined c:\program files\microsoft sdks\windows\v5.0\include\winnt.h    5940    5   

could you please tell me what error is this..and where I am going wrong?? thank you.

Why do i have to include stdafx.h everytime in visual C++ 2010 express. Evertime i make a project i have to include that damn header, whats so special about it and how can i avoid including it and still compile my program. I have tried to leave it out but it doesnt want to compile then givving an arror about forgetting to include stdafx.h.

And if you know how to compile a single source file without having to create a new project i will epreciate it.
I am using Visual Studio C++ express 2010

Oh and if you know where to get a good tutorial about making a simple server-client side TCP chat program in C++ with winsock2.h

Thanks...

Delete or clear all from linked-list?

by BryantFury at 04:55 AM, 05/18/2012

Hi ive made a code where a user makes a list and then displays it. he may also delete objects one by one.

suppose i wished to clear all in one go. How would i go about doing this? thank you in advance. my code is below. all works except the clear all option does nothing.

#include <iostream>
using namespace std;
struct node {
    string pro[10];
    string product;
    node *link;
};

node* buildListForward()
{
  node *first,*newNode, *last;
  string num;
  cout<<"\nEnter Products\nEnter 'quit' when done\n";
  cin >>num;

  first=NULL;
  while(num!="quit")
  {
    newNode = new node;     
    newNode->product =num;
    newNode->link = NULL;
    if(first==NULL)             
    {
    first = newNode;
    last= newNode;
    }
    else
    {
      last->link = newNode;
      last = newNode;
    }
        cin>>num;
   }
   return first;
}

node* deleteNode(node *head,string delItem)
{
  node *current,*prev;
  bool found=false;
  current = head;
  prev = head;
  while(current!=NULL && !found) {     
    if(current->product==delItem) found = true;
    else {
          prev = current;
          current = current->link;
     }
  }
  if(found) {
    if (current==head) head = current->link;
    else
     prev->link = current->link;
    delete current;
  }
  return head;
}

int main() {
    node *head, *current;
    string num;
    int pos;
    int menu;
    bool quit=false;
    do{ 
     cout<<"1.....Build List"<<endl;
     cout<<"2.....Delete Item"<<endl;
     cout<<"3.....Display"<<endl;
     cout<<"4.....Logout"<<endl;
     cout<<"5.....Quit"<<endl;
     cout << "Enter choice: ";
     cin >> menu;

     switch(menu){
            case 1:cout<< "\nBuild List"<<endl;
              head = buildListForward();
            system("cls");
                     break;

            case 2:cout<< "\nDelete Item"<<endl;
                cout<<"Enter number to delete\n";
                cin>>num;
                head = deleteNode(head,num);
             system("cls");
                     break;  

            case 3:cout<< "\nDisplay Item"<<endl;
            current = head;
            while(current!=NULL) {
            cout<<current->product<<endl;
            current = current->link;
            }
            system("pause");
            system("cls");
                     break;
            case 4:cout<<"Clear All";
            system("cls");
            break; 
            case 5:quit=true;
                     break;
            default:cout<<"Invalid entry must be 1..5"<<endl;
            }
    }while(!quit);    
    system("pause");
    return 0;
}

Creating log file in Header

by BigEEter at 13:03 PM, 05/17/2012

Hi. I am wondering if a log file can be created in a header which is associated with a try-catch block. Below is my stripped down code for the log_header.h and log_test.cpp

Here is log_header.h

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

class thrower{
    fstream myfile2;
public:
    void errormessage();
};

void thrower::errormessage(){
    cout<<"Thrower works\n";
    ///////These are log commnands////////
    myfile2.open("C:\\error2.txt",ios::out);
    myfile2<<"Message 2\n"<<endl;
    myfile2.close();
    ////////////////////////////////////////
};

Here is log_test.cpp

#include"log_header.h"
#include<fstream>

#include<iostream>
using namespace std;

thrower t;
int main(){

    fstream myfile;

    try{
        int y=4;
        if (y<5){
            throw t;
        }
    }
    catch(thrower tt){
        tt.errormessage();
        myfile.open("C:\\error.txt",ios::out);
        myfile<<"Message \n"<<endl;
        myfile.close();
    }
    return 0;
}   

If I comment out all of the log_header.h lines that contain "myfile2", then the "myfile" object in the log_test.cpp gets updated and the error message from the errormessage method is printed. It would be more elegant if the log file creation was contained in the header. Please assist.

Creating log file in Header

by BigEEter at 13:01 PM, 05/17/2012

Hi. I am wondering if a log file can be created in a header which is associated with a try-catch block. Below is my stripped down code for the log_header.h and log_test.cpp

Here is log_header.h

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

class thrower{
    //fstream myfile2;
public:
    void errormessage();
};

void thrower::errormessage(){
    cout<<"Thrower works\n";
    ///////These are log commnands////////
    //myfile2.open("C:\\error2.txt",ios::out);
    //myfile2<<"Message 2\n"<<endl;
    //myfile2.close();
    ////////////////////////////////////////
};

Here is log_test.cpp

#include"log_header.h"
#include<fstream>

#include<iostream>
using namespace std;

thrower t;
int main(){

    fstream myfile;

    try{
        int y=4;
        if (y<5){
            throw t;
        }
    }
    catch(thrower tt){
        tt.errormessage();
        myfile.open("C:\\error.txt",ios::out);
        myfile<<"Message \n"<<endl;
        myfile.close();
    }
    return 0;
}   

If I comment out all of the log_header.h lines that contain "myfile2", then the "myfile" object in the log_test.cpp gets updated and the error message from the errormessage method is printed. It would be more elegant if the log file creation was contained in the header. Please assist.

random

by Garrett85 at 11:53 AM, 05/17/2012

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

int rand_0toN1(int n);

int main()
{
    int n, i;
    int r;

    srand(time(NULL));      // set a seed for random-number generation.

    cout<< "Enter number of dice to roll: ";
    cin>> n;

    for(i = 1; i <= n; i++)
    {
        r = rand_0toN1(6) + 1;

        cout<< r << " ";
    }
    system("pause");
    return 0;
}

// random 0 to n1 function
int rand_0toN1(int n)
{
    return rand() % n;
}

I'M having trouble understanding a few lines of this program, the first one is srand(time(NULL));
I'M assuming srand is the function so what is time in this code. Also, if this line is generating a random number where is it storing the number, I don't see a variable anywhere.
And the line r = rand_0toN1(6) + 1, what's the + 1 all about? Thanks.

Need Help in C++

by selfuser at 08:29 AM, 05/17/2012

Hai i need help in C++.. this is my code. By using this code I have to alter it and do Evolutionary Text/ Poem.
The poem is :
**“Berburu ke padang datar,
Dapat rusa berbelang kaki,
Berguru kepalang ajar,
Bagai bunga kembang tak jadi.” **

**There are 3 files.. Evo0.cpp(below code), mtrand.h and mtrand.cpp Click Here **

#include <iostream>
#include <ctime>
#include <windows.h>
#include <fstream>
#include "mtrand.h"

using namespace std;

int main () {
    const int chromosome_length = 40;
    const int pop_size = 20;    
    int max_generation = 200;
    int mutate_position;        // pos to mutate
    int xover_position; // pos to xover
    int rand_val;       // to hold random value, i.e. allele
    MTRand_int32 mt;    // create MTRand object
    mt.seed( time(NULL) ); // seed the RNG object
    MTRand mtreal;  // create MTRand object, real value of [0, 1) interval
    mtreal.seed( time(NULL) ); // seed the RNG object

    int pop[ pop_size ][ chromosome_length] = {0}; // un-init pop
    int mating_pool[ pop_size ][ chromosome_length] = {0}; // un-init pop

    int best[ chromosome_length ] = {0}; // un-init pop
    int best_fitness = 0; // var to store best[] fitness value
    int total_fitness = 0;  // var to store total sum of fitness values
    double avg_fitness = 0.0;   // var to store avg fitness value

    int fitness_values[ pop_size ]; // array to store fit value for all ind

    ofstream myfile;
    myfile.open ("output.txt");

    // randomize pop here!----------------------------------------
    for ( int i = 0; i < pop_size ; i++ ) {
        cout << i << ": ";

        for ( int j = 0; j < chromosome_length; j++ ) {
            // get random value 
            //srand ( time(NULL) );     /* initialize random seed */            

            rand_val = 0; // re-init random value
            rand_val = mt() % 2;    /* generate random value - 0 or 1 */

            pop[ i ][ j ] = rand_val;

            //Sleep(1000);

            cout << pop[ i ][ j ];
        } // end for - inner loop

        cout << endl;
    } // end for - outer loop
    cout << endl;

    // randomize pop ENDS!----------------------------------------

    int gen_num = 0; // init gen num
    while ( gen_num < max_generation ) {
        // re-init total & avg fitness values
        total_fitness = 0;
        avg_fitness = 0.0;

        // output best ind here - use (highest) fitness value
        int ind_fitness; // declare var for fitness
        for ( int i = 0; i < pop_size; i++ ) {
            ind_fitness = 0; // re-init fitness value

            for ( int j = 0; j < chromosome_length; j++ ) {              
                ind_fitness = ind_fitness + pop[ i ][ j ];
            } // end for - calc fitness value for one ind

            fitness_values[ i ] = ind_fitness;  // store every ind fitness

            //compare current ind with (currently) best ind here
            if ( ind_fitness > best_fitness ) {
                for ( int k = 0; k < chromosome_length; k++ ) {
                    best[ k ] = pop[ i ][ k ];
                } // end for loop - copy best ind

                best_fitness = ind_fitness; // copy the current fitness into best ind
            } // replace the best ind with current ind

            // output (currently) best ind here - just to have a look!
            cout << gen_num << ":" << i << " Current best ind: ";
            // loop to print out best chromosome
            for ( int m = 0; m < chromosome_length; m++ ) {
                cout << best[ m ];        
            } // end for - print out best chromosome
            cout << gen_num << ":" << i << " Current Best Fitness value: " << best_fitness << endl;

            // summation of ind fitness values
            total_fitness = total_fitness + fitness_values[ i ];

        } // end for - calc fitness value for all ind

        // avg fitness here!
        avg_fitness = total_fitness / pop_size;

        // dump data here!
        myfile << gen_num << " " << best_fitness;
        myfile << " " << avg_fitness << endl;     

        // parent selection----------------------------------------
        int parent1;
        int parent2;
        int selected;
        int z = 0;
        int k = 2;      // tournament selection parameter

        // parent - tournament selection method
        for ( int count = 0; count < pop_size; count++ ) {
            parent1 = mt() % pop_size;  /* generate random value, [0,pop_size) */
            parent2 = mt() % pop_size;  /* generate random value, [0,pop_size) */

            if ( fitness_values[ parent1 ] > fitness_values[ parent2 ] ) {
                selected = parent1;
            } else {
                selected = parent2;
            }

            for ( int m = 0; m < chromosome_length; m++ ) {          
                mating_pool[ z ][ m ] = pop[ selected ][ m ];
            } // end for - copy winner into parent pool

            z = z + 1; // increment parent pool counter
        } // end for - loop each two individual
        // print out parent pop
        // parent selection ENDS----------------------------------

        // xover here----------------------------------------
        int p1[ chromosome_length ]; // temp parent1
        int p2[ chromosome_length ]; // temp parent2
        int offspring[ pop_size ][ chromosome_length ]; // offsprings array
        int j = 0; // counter for index of 2nd parent
        // prob of recombination
        double Pc = 0.6;    // arbitrary threshold value (higher than Pm)
        double prob_recombine;  // var to hold the generated prob

        for ( int i = 0; i < pop_size; i = i + 2) {
            j = i + 1;

            for ( int k = 0; k < chromosome_length; k++ ) {
                p1[ k ] = mating_pool[ i ][ k ];
                p2[ k ] = mating_pool[ j ][ k ]; // p2 gets the next ind
            }

            //copy the chromosome array, i.e. the ind
            for ( int z = 0; z < chromosome_length; z++ ) {
                offspring[ i ][ z ] = p1[ z ];
                offspring[ j ][ z ] = p2[ z ];
            }

            // get random position here for xover   
            // NO NEED to seed RNG object, already hv list of random numbers
            //mt.seed( time(NULL) ); // seed the RNG object         

            xover_position = 0; // re-init pos value
            // NEED to CHECK LOWER VALUE: should be
            // 0 till (chromosome_length - 1)           
            xover_position = mt() % chromosome_length;  /* generate xover position */

            prob_recombine = mtreal();

            // do recombination if prob LESS than threshold!
            if ( prob_recombine < Pc ) {
                for ( int counter = xover_position; counter < chromosome_length - 1; counter++ ) {
                    offspring[ i ][ counter ] = p2[ counter ];
                    offspring[ j ][ counter ] = p1[ counter ];
                } // end for - loop for xover starting from xover_position
            } // else here is just to display, actually no need!
            else {  // DO NOT do recombination if prob GREATER than threshold!
                // maintain offspring i and j values as is!
                cout << gen_num << ":" << i << " did not do recombination" << endl;
            }
        } // end for - loop select 2 parents        
        // xover ENDS----------------------------------------

        // mutate here----------------------------------------
        // prob of mutation
        double Pm = 0.4;    // arbitrary threshold value (lower than Pc)
        double prob_mutate; // var to hold the generated prob

        // go thru ALL ind
        for ( int i = 0; i < pop_size; i++ ) {
            // get random position here 
            // NO NEED to seed RNG object, already hv list of random numbers
            //mt.seed( time(NULL) ); // seed the RNG object         

            mutate_position = 0; // re-init pos value
            mutate_position = mt() % chromosome_length; /* generate position */

            prob_mutate = mtreal();

            // do mutation if prob LESS than threshold!
            if ( prob_mutate < Pm ) {
                // bit-flip the value at position
                if ( offspring[ i ][ mutate_position ] == 0 ) {
                    offspring[ i ][ mutate_position ] = 1;
                } else {
                    offspring[ i ][ mutate_position ] = 0;
                } // end if-else bit-flip
            } // else here is just to display, actually no need!
            else { // DO NOT do mutation if prob GREATER than threshold!
                cout << gen_num << ":" << i << " did not do mutation" << endl;
            }
        } // end for - mutate all ind
        // mutate ENDS----------------------------------------

        // survivor select here----------------------------------------
        // since offspring is NOT in pop[][],
        // so MUST write back into pop[][]
        for ( int i = 0; i < pop_size; i++ ) {
            for ( int j = 0; j < chromosome_length; j++ ) {
                pop[ i ][ j ] = offspring[ i ][ j ];
            } // end for - loop each ind 
        } // end for -loop write offspring into pop
        // survivor select ENDS----------------------------------------

        gen_num = gen_num + 1; // increment gen num
    } // end while loop - GA finish

    // output end best ind here
    // output (the final) best ind here - just to have a look!
    cout << "FINAL best ind: ";
    // loop to print out best chromosome
    for ( int j = 0; j < chromosome_length; j++ ) {
        cout << best[ j ];        
    } // end for - print out best chromosome

    cout << " FINAL Fitness value: " << best_fitness << endl;

    myfile.close();

    return 0;
} // end main

Class Vector Insert / Constructor

by Sunshine2011 at 06:15 AM, 05/17/2012

#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

class members
{
 private:
 int Age;
 int Money;

 public:
 void setAge(int age) {Age=age;}
 void setMoney(int money) {Money=money;}
 int getAge()const {return Age;}
 int getMoney()const {return Money;}
 members(int age=0,int money=0): Age(age),Money(money) {}
};

int main()
{
vector<members>v_members;
for(size_t i=0,z=0;i<10;++i,++z)
    {
     if(z!=5) { v_members.push_back(members(50,70)); }
    }
}

I wrote a litte program for a better understanding of a classvector and costructors. It should be ok but there are two questions.

  • How could one insert new elements in the vector ?
  • Would it be a good idea to create the vector within the class / the constructor?
    If so, how could this be done and how could data then be saved in the main?

Do I need to build a type traits(problem of GIL)?

by stereomatching at 06:00 AM, 05/17/2012

template<typename View>
struct pixel_traits;

template<>
struct pixel_traits<gray8c_view_t>
{
  typedef gray8c_pixel_t type;
}

Could I find something like this from gil?Thanks

Multiple data types = LinkedList

by Interista at 03:02 AM, 05/17/2012

Hi im creating a linked list with these data types

etc

string firstname
string surname
int age

would anyone give a simple instruction to put these in a new node as i have tried everything but still doesnt work so far i have done this

nodeType first,newNode, *last;

cout<<"Name: ";
cin>>name;
cout<<"Surname: ";
cin>>surname;
cout<<"Age: ";
cin>>age;


setVideoInfo(name,surname,age);



  first=NULL;


     newNode = new nodeType;     // create new Node

    newNode->info =(name,surname,age) ;

*This is not all of it but i know the problem lies in the lines above any help would be much appreciated

Thankyou*

_T vs L Macros

by triumphost at 01:36 AM, 05/17/2012

What should I be using? Should I be using _T? or L? Or Neither?
I know some functions end with the A for Ansi and some end in W for the Unicode version but I have no clue what I want to use.

if I use _T would I have to change all my strings to wstrings? if I use L would I have to do that too?

if I use _T would I have to change all my MessageBoxes to MBW or MBA or just MB? What about StrLen would I change that too? Also some functions require lengths vs character bytes. Does this affect it?

Ohh and I almost forgot. What is the difference between _Unicode and Unicode :S

C++ coding gone wrong

by tweeeter at 19:58 PM, 05/16/2012

I need to modify the following program to store person objects instead of integers. Include a function to input person data from the keyboard in the person class (similar to the readRecord() function). Also add a non class function to display the list contents.

Include a separate search function (search on the name of the person) which returns the position in the list of the item if found

Setup a menu to access the different functions such as:
1 Build a list
2 Search list
3 Add to list
4 Delete from list
5 Display list

This is the code:

#include <iostream>
using namespace std;
// Linked list using structures
struct nodeType {
    int info;
    nodeType *link;
};
nodeType* buildListForward()
{
  nodeType *first,*newNode, *last;
  int num;
  cout<<"enter numbers";
  cin >>num;
  first=NULL;
  while(num!=-999)
  {
    newNode = new nodeType;     // create new Node
    newNode->info =num;
    newNode->link = NULL;
    if(first==NULL)             // special case empty list
    {
    first = newNode;
    last= newNode;
    }
    else
    {
      last->link = newNode;
      last = newNode;
    }
        cin>>num;
   }
   return first;
}
nodeType* buildListBackward()
{
  nodeType *first,*newNode;
  int num;
  cout<<"enter numbers";
  cin >>num;
  first=NULL;
  while(num!=-999)
  {
    newNode = new nodeType;     // creat new node
    newNode->info =num;
    newNode->link = first;

    first = newNode;            // keep adding at beginning

        cin>>num;
   }
   return first;
}
nodeType* deleteNode(nodeType *head,int delItem)
{
  nodeType *current,*prev;
  bool found=false;
  current = head;
  prev = head;
  while(current!=NULL && !found) {          // search loop
    if(current->info==delItem) found = true;
    else {
          prev = current;
          current = current->link;
     }
  }
  if(found) {
    if (current==head) head = current->link;// special case delete head
    else
     prev->link = current->link;
    delete current;
  }
  return head;
}
nodeType* insert(nodeType *head, int item)
{
  nodeType *current,*prev,*newNode;
  bool found=false;
  newNode = new nodeType;
  newNode->info = item;
  newNode->link = NULL;
  current = head;
  prev = head;
  while(current!=NULL && current->info<item) {  // search loop

          prev = current;
          current = current->link;

  }

    if (current==head) {            // special case add at head
        newNode->link = current;
        head = newNode;
    }
    else {
     prev->link = newNode;
     newNode->link = current;
    }

  return head;
}
int main() {
    nodeType *head, *current;


    system("pause");
    return 0;
}

Any help will be greatly appreciated

Access violation reading location

by yoni0505 at 13:29 PM, 05/16/2012

Hi,

I'm experimenting with A Star pathfinding.
I'm having a problem with a function. I'm getting the next error after running it:

Unhandled exception at 0x76ec15de in A Star Pathfinding.exe: 0xC0000005: Access violation reading location 0x08e463a8.

the function's code is:

void addAdjacent(list* oList, list* cList, int tileMap[][40])
{
    node* newParent = oList->nlist[oList->index];
    for(int y=-1; y <= 1; y++)
    {
        for(int x=-1; x <= 1; x++)
        {
            if(y == 0 && x==0){continue;}//skip checking the center node

            node newNode;
            newNode.parent = newParent;
            newNode.setPos(newParent->x + x,newParent->y + y);
            if(validNode(&newNode, tileMap) == true && inList(&newNode, cList) == false)
            {
                oList->addNode(&newNode);
                tileMap[newNode.y][newNode.x] = 4;
            }
        }
    }
    cList->addNode(newParent);//add center node to closed list
    tileMap[newParent->y][newParent->x] = 5;
}

When I tried to debug it seems that the error happened in the last loop.

When I press "continue" after the error, the error seems to happen in tidtable.c in the line

PFLS_GETVALUE_FUNCTION flsGetValue = FLS_GETVALUE;

I don't know what cause this problem. I tried to google for the errors and couldn't find a solution.
Help will be appreciated!

Hello great people, I have a challenge passing array into functions..
I will be very grateful for quick responses.. THANKS

how to read a file with a particular encoding

by cppgangster at 11:42 AM, 05/16/2012

Dear all,
How to read a file with particural encoding like UTF -8 or UTF- 16. Do I need to use some special library?

Pointer ++ (plus plus) operator priority

by FelineHazard at 08:52 AM, 05/16/2012

Hi all,
I have a rather basic C/C++ question about the priority of the ++ operator in regard to pointers. Note the following code (joining two strings):

#define LENGTH 255
void mystrcat (char *base, char *add) {
    while(*base) ++base;
    while( *(base++) = *(add++) );
}
int main() {
    char name[LENGTH]="Feline";
    char lastname[LENGTH]=" Hazard";
    mystrcat(name,lastname);
    printf("My name is: %s", name);
return(0);
}

Now the function mystrcat joins lastname to name but I don't understand exactly why. At the end of the 1st while loop (line 3) base should be pointing to the terminal zero (\0) of the base string, right?
Now, the second while loop (line 4) I don't understand. What happens first? The assignment (*base)=(*add) and the increment of pointer positions? Or the other way around? First increment of position, and then assignment. I don't quite understand the prioritizing of actions in the 4th line.

Thanks,
-FH

Get variable from other program window

by rannamaa at 08:07 AM, 05/16/2012

Im making a program in wich I need to monitore (import) a variable (number from an other program window every time the variable changes. There are very much other information in this window but I only want this number that is occuring at a sertain position in the window. How do I do this? with hooks?
Greatful for answeres.

Few questions about C++

by Hellblazer. at 06:26 AM, 05/16/2012

Hello everyone, I want to start learning C++, because that's what we do at school and I really need to know it. But there's a problem, I don't know where to start from, what to do and such. At school I can't understand anything from the teacher, so that won't work. I tried reading some books, but they don't explain very well, or I just simply can't understand.

I come from a poor country, so we use TurboC++ to code at school, it's really dumb, but yeah, can't do anything about it.

At school, we do exercises with numbers and arrays, for example, the program reads numbers until meeting 13, show the even and uneven ones, show the average, show the negative/positive ones. Or the program reads numbers until n, show the sum of the middle numbers, like 12345, show the sum of 3 and 4. Or the minimum and maximum value of something.

Can anyone recommend me what to do to properly learn C++ and do these exercises? I'll have a lot of C++ exams in the future and I wanna do well, also I need this knowledge of C++ for later use.

Thanks for reading, sorry for the spelling mistakes and sorry if it already has been answered or I posted in the wrong place!

Basic Array

by Valiantangel at 02:49 AM, 05/16/2012

double a [3]={1.1,2.2,3.3};
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
a[1]=a[2];  
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;

ans to the above is
1.1 2.2 3.3
1.1 3.3 3.3

I am new to array. Please expalin why a[1]=a[2] gave me 3.3 3.3.
thank you

Having Issues with Login System

by nathaniscool99 at 14:09 PM, 05/15/2012

Hello, I am trying to create a Login system, so far it writes users correctly however it doesn't seem to be reading it correctly as it always claims the username/password is incorrect even though when I check the file it is.

Could someone help, thanks!

class TestLogin
{
    public:
    char name[16];
    char pword[10];

        void sendname();
        void sendpassword();
};

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

using namespace std;

void TestLogin::sendname()
{
    cout << "Enter your desired username(max 16 characters): ";
    cin >> name;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
};

void TestLogin::sendpassword()
{
    cout << "Enter your password(max 10 characters): ";
    cin >> pword;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
};

int ListMenu()
{
    int option;
    cout << "Welcome to the login menu..." << endl;
    cout << "\tPress '1' to login." << endl;
    cout << "\tPress '2' to register." << endl;
    cout << "Your option: ";
    cin >> option;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    return option;
};

int main()
{
    ifstream readFile ("list.txt");
    ofstream writeFile ("list.txt", ios::app);
    TestLogin charInfo;
    do
    {
        int option = ListMenu();
        cout << endl;

        if(option == 1)
        {
            string username;
            string password;
            string temp;
            string temp1;

            if(readFile.is_open())
            {
                cout << "Enter Name: ";
                cin >> username;
                cout << "Enter Password: ";
                cin >> password;
                cout << endl;
                readFile >> temp;
                cout << "scanning for username...";


                if(username == temp)
                {
                    cout << "\nusername found, checking password" << endl;

                    readFile>>temp1;
                    if(password == temp1)
                    {
                        cout << "Welcome " << username << "!" << endl;
                        break;
                    }
                }
                else
                {
                    cout << "Invalid username or password." << endl;
                }
                readFile.close();
            }
        }
        cout << endl;
        if(option == 2)
        {
            charInfo.sendname();
            cout << endl;
            charInfo.sendpassword();
            cout << endl;
            if (writeFile.is_open())
            {
                writeFile << charInfo.name << endl;
                writeFile << charInfo.pword << endl;
                writeFile.close();
            }
            else
            {
                cout << "Unable to open file";
            }
        }
    }while(1);
    return 0;
}

SoRayPickAction in Open Inventor?

by dark_sider_1 at 12:13 PM, 05/15/2012

Hi there,

I'm trying to implement SoRayPickAction that will, when the mouse is clicked, select a particular node so then I can translate, rotate, etc. I have three nodes: desk, lamp, and frame (picture frame). However, I don't think that my code is at all right. I also have various methods such a MouseButtonCallback (which will check if the mouse is clicked and then use a navigator) and MouseMoveCallback (same idea). So here's the code that I have, but do you have any suggestions? Right now, well, it doesn't do anything.

SbViewportRegion viewport(400,300); 
    SoRayPickAction m(viewport); 
    m.setRay(SbVec3f(0.0,0.0,0.0), SbVec3f(0.0,0.0,-1.0));
    m.apply(callback_node);
    const SoPickedPoint *mpp = m.getPickedPoint(); 
    if(mpp != NULL) {
        std::cout << "test" << std::endl;
    }

Might you also know of an action in OpenInventor that can "place" a node in the scene, i.e. place the lamp on top of the desk, frame on the wall, etc. Is it with paths? I don't even know what I'm looking for, unfortunately. Thanks so much for your help!!

Line-rect collision detection

by Chuckleluck at 10:14 AM, 05/15/2012

Hello,
I'm fairly new to programming, and I'm not exactly sure how to do line-rect collision detection. If it helps, I'm using SFML 2. Can someone explain to me how I would go about coding line-rect collision detection?
Thanks in advance.

Problem with getline()

by lucaciandrew at 04:44 AM, 05/15/2012

I have this function:

void read(){
    int id;
    string desc;
    string title, type;
    cout<<"Movie's id: ";
    cin>>id;
    cout<<"Movie's title: ";
    cin>>title;
    cout<<"Movie's description: ";
    getline(cin, desc, '\n');
    cout<<"Movie's type: ";
    cin>>type;
    cout<<"You have typed in: "
        <<id
        <<" "
        <<title
        <<" "
        <<desc
        <<" "
        <<type
        <<".\n";
}

and my problem is that in the desc field, when I must insert something, it skips over, passing to the type field, not letting me insert anything. I've tried in another project only with the getline(cin, desc, '\n') and it worked, it took all the line, but here it just skips the field. My question is this: why does this thing happens? and did I do something wrong?
10x.

C++ Qt application slow startup

by Eagletalon at 03:02 AM, 05/15/2012

Hey Everyone,

I have run into a bit of a problem with regards to application startup...

I have written a C++ application with QT libraries that uses active QT to communicate with our ERP system in our business, the requirements are that any application we use needs to communicate its variables into this application by means of an argument list that uses unique splitters, and the application then checks the command (seperate argument) and handles the variables and inserts into XML to communicate them to the ERP

my issue is this, with larger argument lists (larger applications and more intricate functionality) the application take much longer to start up, functionality from the very first coding line to the finish is quick, as quick as I can possibly get it... but the startup is way too slow...

Is there anything I can do to speed up the startup? can this be caused by the large arguments? or could it be something else, I thought of dll loading as a possibility though I have tested running the application over a network and on the same machine (because to my knowledge dll loading takes even longer over a network) but I found exactly the same result

Thanking everyone in advance for the assistance

Passing ANY function to another function.

by triumphost at 16:33 PM, 05/14/2012

Currently I use:

DWORD ThreadProc(LPVOID lpParameter)
{
    void (* function)() = (void (*)())lpParameter;
    function();
    return 0;
}

void Threading(HANDLE &hThread, DWORD &ThreadID, void* FunctionToPass)
{
    hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, (void*)FunctionToPass, 0, &ThreadID);
}

And I want to call it like:

Handle hThread; DWORD ThreadID;

Threading(hThread, ThreadID, AnyFunctionHere);

That way my Threading Function will create a thread and run any function. How can I pass it a function that has 0 or more parameters?

type casting confusion

by Garrett85 at 15:27 PM, 05/14/2012

I'M working my way through the book "C++ without fear by Brian Overland" and there are two small programs with to totally different types of type casting and the book fails to explain the difference, please help me understand. Thanks. The first one is on a while loop and the second one is on a for loop.

prime1.cpp

using namespace std;

int main()
{
    int n;      // number to test for prime-ness
    int i;      // loop counter
    int is_prime;   // boolean flag

    // assume that a number is prime untio proven otherwise

    is_prime = true;

    // get a number from the keyboard

    cout<< "Enter a number and press ENTER: ";
    cin>> n;

    // test for primeness by checking for divisiblity by all whole numbers from 2 to sqrt(n)

    i = 2;

    while(i <= sqrt(static_cast<double>(n)))
    {
        if(n % i == 0)
            is_prime = false;
        i++;
    }

    // print results

    if(is_prime)
        cout<< "Number is prime.";
    else
        cout<< "Number is not prime.";

    system("pause");
    return 0;
}

prime2.cpp

#include <Stdafx.h>
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int n;
    int i;
    int is_prime;

    // assume that a number is prime until proven otherwise

    is_prime = true;

    // get a number from the keyboard
    cout<< "Enter a number and press ENTER: ";
    cin>> n;

    // test for prime-ness

    for(i = 2; i <= sqrt((double) n); i++)
    {
        if(n % i == 0)
            is_prime = false;
    }

    // print results

    if(is_prime)
        cout<< "Number is prime.";
    else
        cout<< "Number is not prime.";

    system("pause");
    return 0;
}

Making DOS Window Disappear

by iismitch55 at 14:08 PM, 05/14/2012

I have been researching ways to make a DOS window disappear when starting a program. I have solved this, by using getconsolewindow() and setwindow(). The thing is, I still get a blip where the DOS appears for a couple miliseconds. Is there a way to fix that?

Clip of code:

#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <iostream>
int main()
{
HWND hWnd1 = GetConsoleWindow();
ShowWindow( hWnd1, SW_HIDE );

return 0;
}

Need a little help please:
i have been trying to complete this for a couple days but i get more and more confused everytime i try.

When an object is falling because of gravity, the following formula can be used to determine the distance the object falls in a specific time period.
D = ½ gt^2

The variables in the formula are as follows: d is the distance in meters, g is 9.8, and t is the amount of time in second that the object has been falling.
Write a function named fallingDistance that accepts an object’s falling time (in seconds) as an argument. The function should return the distance, in meters, that the object has fallen during that time interval. Write a program that demonstrates the function by calling it in a loop that passes the values 1 though 10 as arguments, and displays the return value.

*Additional to this problem my prof wants two functions that calculate the falling distance.
function 1 passes arguments by value
function 2 passes argument by reference

outputs should be in form of a table

whats confusing is the prof established that in the main it should resemeble like this:
for(--------------)
call (by value)
output

for(---------------------)
call (by reference)
output

call by ref works fine but call by value only works when i put double d as global but then it only comes back as 0's in the output. its not reading the equation
my code so far:

Inline Code Example Here

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

void fallingDistance2(double &);
double fallingDistance1(double);
const double g = 9.8;
int t;
double d;

int main()
{


    cout<<"calculated by passby values.\n";
    cout<<"Time \t\t Distance\n";
    cout<<"-------------------\n";
    for (t=1;t<=10;t++)
    {
        fallingDistance1(d);
        cout<<t<<"\t\t"<<d<<endl;
    }


    cout<<"calculated by reference values.\n";
    cout<<"Time \t\t Distance\n";
    cout<<"-------------------\n";
    for (t=1;t<=10;t++)
    {
        fallingDistance2(d);
        cout<<t<<"\t\t"<<d<<endl;
    }


    return 0;
}


double fallingDistance1(double d)
{
    d=0.5*9.8*t*t;
    return d;
}

void fallingDistance2(double &refd)
{
            refd=0.5*9.8*t*t;
}

queue read tab delimited

by PuQimX at 06:39 AM, 05/14/2012

i have read a txt file into queue just like below example which is i can do it.. the problem is i how to read Tab Delimited Files which i want file size to multiple by 0.6... because i want to create handle a printer simulation using queue...sorry for my english

Name of File   Time accepted   File size (KB)
Exercise.cpp    8.00 am     1.2
Report.doc      8.00 am     3.4
Test.doc        8.10 am     5.0

Help reading a file into a 2D array

by nathaniscool99 at 06:38 AM, 05/14/2012

Hello I am looking to read a file into a 2d array to show which spaces have been taken/ haven't taken whiey will show a # if not taken and a T if taken, so far I just have a text file I created which shows like this:

T # # T
T T T #

All I am trying to do at the moment is to read this into a 2d array and display it as above, later on I will allow users to choose a position and take a space of the layout (changing a T to a #) and then I will want to save it to the file to make the changes.

But at the moment all I want to do is show it, this is what I have so far, I appologize if it's messy, I have made so many changes now to try and get it to work.

I hope someone can offer som guideance.

void Layout::layoutset(void)
    {   

ifstream myFile ("layout.txt", ios::in);
myFile.precision(2);
myFile.setf(ios::fixed, ios::showpoint);

myFile >> spaceLayout[2][5];
while (!myFile.eof())


myFile >> //Don't know what to put here
while (!myFile.eof())
{
for (int r = 0; r<2; r++)
{
for (int c = 0; c < 5; c++)
{
spaceLayout[r][c] = //?Don't know what to put here
}
}
}
myFile.close();
} 

Problem with c++ interface (resedit)

by bufospro at 05:00 AM, 05/14/2012

Hi all,
I have to make a project on my School until 18th of May.

I am using resEdit to make graphics for a c++ program. But there ara a lot of cases that the program crashes.

Could you help me ?

I don't know to use resEdit good so ..

Please if you have time, send me a private message

Raster operation. From one window to another

by 330xi at 01:17 AM, 05/14/2012

Hi!
In my program MFC Doc/view one view constantly displaying what the camera is "seeing". After some event I want to show in the other window - dialog the image that has been in the view in the moment of event.

I have code in Dialog window that succesfully draws pictures from disk. However it starts it's work with Handle and "LoadImage". When I try to pass a HANDLE from view no errors occure but no picture displays. The same situation when I pass CBitmap * with some modification of code.
Exploring structures I found that every bit of data like "Height", "Width" goes fine. But it seemed to me that there are some problems with pointer to picture data. Si I decided to copy data from pointer in view to pointer of picture data in dialog manualy with memcpy()

void CEx07bView::OnAppAbout()
{
    CClientDC dc(this); 
    CBitmap *pB;
    BITMAP bm;
    pB = dc.GetCurrentBitmap();
    pB->GetObject(sizeof(bm),(LPSTR)&bm);   

    CAboutDlg aboutDlg(bm); //bm - just some flag for tetsing

    aboutDlg.picture.tBm.bmBitsPixel = bm.bmBitsPixel;
    aboutDlg.picture.tBm.bmHeight = bm.bmHeight;
    aboutDlg.picture.tBm.bmPlanes = bm.bmPlanes;
    aboutDlg.picture.tBm.bmType = bm.bmType;
    aboutDlg.picture.tBm.bmWidth = bm.bmWidth;
    aboutDlg.picture.tBm.bmWidthBytes = bm.bmWidthBytes;
    memcpy(aboutDlg.picture.tBm.bmBits,bm.bmBits,((((aboutDlg.picture.tBm.bmWidth * (aboutDlg.picture.tBm.bmPlanes * aboutDlg.picture.tBm.bmBitsPixel)) + 31) & ~31) / 8)* aboutDlg.picture.tBm.bmHeight);  
    aboutDlg.DoModal();     
}

And when I get "Access violation writing location 0x000000a4". 0x000000a4 - is the start address of tBm.bmBits by the way.

So questions)
What can be a good conception of realising my idea, generally? Did I choose right strategy or i should solve this problems in some other way? Just In common words, can someone show me the goodstyle direction or so?

And just practice question about this violation in memcpy. Howto copy this bits correctly in physically another memory in ohter structure?

Thanks in advance!

help me

by rahim_fayaz at 23:06 PM, 05/13/2012

Hi

I am getting this error when running a very similar code like the
below.
I have memory problem,but i dont know how can solve it.
please help.

Thanks in advance.

///////////////////////////////////////////
~~~~~~~ERROR~~~~~~~~

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted

///////////////////////////////////////////
~~~~~~~~Code~~~~~~~~~

int main(){
  /** Declare classes **/
  for(long int i = 0 ; i < 50000 ; i++){
    class Rahim   *rahim  = new Rahim( (unsigned)(i));
    class Bahram  *bahram = new Bahram;
    class Asgar   *asgar  = new Asgar;
    /*****Body of the code******/   
    throw( asgar, bahram , Rahim );
    delete (bahram);
    delete (Rahim);
    delete (asgar);
      }//end for
      return 0;
   }
  void throw(class Asgar *asgar, class Bbahram  *bahram ,class Rahim *Raahim ){
 /** Declare variables **/
  long int time; 
  long int step = 1999;
  /**     Time Loop         **/
  for( time = 0 ;time < GT ;time++ ){ 
    get_bahram( bahram, Rahim );
    asgar -> get_coordinates ( bahram , time );
    if(step == time){
      long int time_Rg = (step + 1);
      asgar -> calculate_r  ( time_Rg );
      step += 2000;
    }//end if
 } //end for
} //end function 
.

.
.
/**************************/

windows form draw only portion of an image

by jonnyboy12 at 21:46 PM, 05/13/2012

Hello all. I have come to the conclusion that when i try to use images for backgrounds in my windows forms, these images have to be exactly the same size as the form or else when i move the form it will cause the form to shake. The problem with doing this is when i maximize the form the texture image i used as a background then will tile and repeat over and over to match the size of the form. What i want to do , is to use a very large and complete texture or image for background, but only load in part of it and that part it the forms width and height. Then when i resize the form to be larger, i can once again draw the image, but an increased ammount of the image from file . So ill only draw part of the image, and thats the part i need and nothing more. I have struggled for days on how this would work. please help thanks for any tips.

I have read a file with around 120k words so i try to do it fast. have seen the:

int x = setvbuf(fp, (char *)NULL, _IOFBF, BSZ);
assert( x == 0 && fp != NULL );

option but it takes more than a second ( 1 mb file) so now i tried this method :

f

open_s (&pFile,DICT,"rb");
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);

// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);

how do i continue from here? buffer holds a list of words and i want to get them one by one as fast as possible because im building a multimap with those words.

need to be something like this:

while(token!=NULL){
        DB.insert(pair<unsigned int,string>((unsigned)strlen(token),token));
        //cout<< buffer;
        strtok_s(buffer,delims,&context);
    }

just getting the words and inserting to a database

thank you!

EDIT:
THIS WORKS :

    char* context   = NULL;
    char  delims[]  = " ,\t\n";
    char* token     = NULL;


    FILE * pFile;
    long lSize;
    char * buffer;
    size_t result;

    fopen_s (&pFile,DICT,"rb");
    if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

    // obtain file size:
    fseek (pFile , 0 , SEEK_END);
    lSize = ftell (pFile);
    rewind (pFile);

    // allocate memory to contain the whole file:
    buffer = (char*) malloc (sizeof(char)*lSize);
    if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

    // copy the file into the buffer:
    result = fread (buffer,1,lSize,pFile);
    if (result != lSize) {fputs ("Reading error",stderr); exit (3);}


    token = strtok (buffer," \n");
    while (token != NULL)
    {
        DB.insert(pair<unsigned int,string>((unsigned)strlen(token),token));
        token = strtok (NULL, " \n");
    }

but takes too long... i need something in 0.5> seconds approximetly... file size is only 1mb

count the number of film instances

by annitaz at 12:39 PM, 05/13/2012

#ifndef FILM_H
#define FILM_H
#include <QString>

class Film {
  protected:
    QString title;
    double dailyRate;
  public:
    Film(QString ti,double dr);
    QString getTitle() const;
    virtual double calculateRental(int num)const;
};

class Video: public Film {
public:
    Video(QString ti,double dr,QString vt,int d);
    QString getTitle() const;
    QString getVideoType() const;
    virtual double calculateRental(int num)const;
protected:
    QString videoType;
    int discount;
};

#endif // FILM_H

Film.cpp

#include "film.h"
#include <QString>

String ti,double dr){
  title=ti;
  dailyRate=dr;
}

 QString Film::getTitle() const {
   return title;
}

 double Film::calculateRental(int num)const {
   return dailyRate*num;
}

 Video::Video(QString ti,double dr,QString vt,int d)
     :Film(ti,dr){


        videoType = vt;
        discount = d;
 }

  QString Video::getTitle() const {
    return title;
 }

  QString Video::getVideoType() const {
    return videoType;
 }

  double Video::calculateRental(int num)const {
    return (dailyRate*num)-discount;
 }

main.cpp

 #include <QtCore/QCoreApplication>
 #include <QtCore/QTextStream>
 #include  "film.h"

 using namespace std;

 int main(int argc, char *argv[]) {
 QCoreApplication a(argc, argv);
 QTextStream cout(stdout, QIODevice::WriteOnly);
 Film f("Top Gun", 10.00);
 // Print out title and rental fee (based on 2 days rental).
   cout << "Title: " << f.getTitle() << endl;
   cout << "Rental Fee: " << f.calculateRental(2)<<  endl;

   cout <<" " <<  endl;//blank line

 Video v("Top Gun", 10.00,"DVD",5);
 // Print out title and rental fee (based on 2 days rental).
   cout << "Title: " << v.getTitle() << endl;
   cout << "Video Type: " << v.getVideoType() << endl;
   cout << "Rental Fee: " << v.calculateRental(2) << endl;

}

how do I count the number of Film instances created? I know is something like that:

static int numOfFilms;
numOfFilms++;

how do I use the code?

How to compile .cpp files from cmd.exe using cl.exe

by eagle_phoenix2 at 11:26 AM, 05/13/2012

I am using visual studio 2010. I wanted to compile my cpp from cmd. I can compile it using "cl file.cpp" comand in visual studio developer command line tool.

But I wanted to compile it from the built in cmd of windows. When I try to use the command "cl file.cpp" it does not recognize the command. I even tried to cd to cl.exe path and run from there but then it gives a mspdb110.dll is missing error.

I herd that we need to put environment variables but I am not able to find anywhere which variables to set.

Creating hotkeys in application VC++ or BorlandC++

by MrEARTHSHAcKER at 10:54 AM, 05/13/2012

Hi,

Can you tell me how can I make my application recognizes when the user presses a button on keyboard?
For example: presses 'S', application prints "Hello.".

I need this information for BorlandC++, but it would be useful even though you provide the same for VC++ :)
(I am not talking about console applications, I need these tips for GUI apps )

Thank you!

MSV C++

by Garrett85 at 10:20 AM, 05/13/2012

I'M trying to compile a very small cout<< console application in MSC C++ but the program flashes up and goes away so quick that I can't see anything that's going on. Below are my headings, what's missing? Thanks.

#include <Stdafx.h>
#include <iostream>

using namespace std;

Please write a program that will asks to give an integer number K that will be higher than 20.
If the number is not higher than 20 then make the program to show a relevant message and then ask to insert again the number K.

After that, depending on the users choice:
If he/she presses 1, it will be shown the sum of numbers from 1 to K.
If the number is 2, it will be shown the odd numbers from 1 to K.
If the number is 3, the program will end.

If any other numbers are inserted then make your code to show a warning message (that the user must insert numbers from 1 to 3) and then the program must do again the process of inserting the number 1-3.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{   
    int k;
    cout<<"\n Insert a number greater than 20. "; 
    cin>>k; 
    cout<<"\n The number is "<<k<<" ."<<endl<<endl;
    while ( k<=20 ) {
     cout<<"It must be greater than 20. Give again the number. ";
     cin>>k; 
     }    

    int num, sum, odd;
    cout<<"\n Now,give a number from 1 to 3. ";
    cin>>num; 
    cout<<endl;  

  switch (num)
    { case 1: {sum = 0;
           for ( int i=num ; i<=k ; i++)
           sum+=i;
           cout<<"The sum from "<<num<<" to "<<k<<" is: "<<sum<<endl;
               }
           break;

      case 2: { int i = 1;
           cout<<"\n The odd numbers from 1 to "<<k<<" are:\n";
           for ( int i=1 ; i<=k ; i=i+2 )
               cout<<i<<"  "; 
               cout<<"\n";
               odd=i++;
              }
           break;

      case 3: 
           break;

      default: {cout<<"The number must be 1, 2 or 3.\n";
                cout<<"\n Give again the number "; 
                cin>>num; cout<<"\n";
                }
           break;
    }    
    cout<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

WriteProcessMemory failing

by citizen5 at 07:44 AM, 05/13/2012

Small part of my code:

GetWindowThreadProcessId(hWnd, &dwID);
hProcess = OpenProcess(PROCESS_ALL_ACCESS, NULL, dwID);
string value =" [_this] exec \"\\newfolder\\scripts\\start.sqf\"";
WriteProcessMemory(hProcess, (LPVOID) 0x09BA3F95, (LPVOID) &value, sizeof(&value), NULL);

I am 100 % sure it has to do with my value being a string but I haven't found anything helpful elsewhere, even though I've searched hard (in my opinion). So please, can anyone help me? I'm still a beginner in programming but a superficial explanation will do :)

Thank you

Problem in identical array

by rafaquatbutt at 06:52 AM, 05/13/2012

Write a program for an application that does not tolerate erroneous input data. Therefore, the data values are prepared by entering them twice by the user. Two lists are made by getting positive integers from the user, separated by a negative number. These two lists of numbers should be identical; if they are not, then a data entry error has occurred.

• Example:
User enters list
17
14
8
-5
17
14
8
The lists are identical. However see the following input

User enters list
17
14
8
-5
17
12
8
Program should show data entry error.

little help need to solve the question, plz urgent

by rafaquatbutt at 06:38 AM, 05/13/2012

we need to solve the following question.

Write a program that asks the user for a word, and then prompts a user for a letter. Your program should count the number of times the letters entered appear in the word, and then continue prompting for new letters. The program should list the letters found and number of times they appear in the word.

Sample Run:
Enter a word: hello
Enter the letter (enter zero to quit): a
There are 0 a’s
Enter the letter (enter zero to quit): h
There are 1 h’s
Enter the letter (enter zero to quit): 0

You found these letters:
h

help me with my coding!

by Miz_LiLO at 05:53 AM, 05/13/2012

I cant display this output..how i can i declare the gender n relate it with my price..i stuck here..oop c++
i have 2 coding for this..which 1 is better..im new in this progrmmer..

void eSalon::priceCurling()
    {
        cout<<"\nYour Gender is: "<<gender;
        if (gender=female)
      {
       cout<<"Long Hair Rm30-RM49"<<endl;
       cout<<"Short Hair RM50-RM100"<<endl;
                           }
      else if (gender=male)
      {
        cout<<"Long Hair RM46-RM70"<<endl;
        cout<<"Short Hair RM20-RM45"<<endl;
        }

or this 1,,

void eSalon::pricePerm()
    {
        cout<<"\nYour Gender is: "<<gender;
        if (gender=female)
      {
        longHair=50-100;
        shortHair=30-49;
                           }
      else if(gender=male)
      {
           longHair=46-70;
           shortHair=20-45;
           }

Reading from a Matrix file

by haven_u at 00:53 AM, 05/13/2012

Hi,
I have a matrix of size of n x m, how can the file be read without any given size, thus making it possible to be read with any given size matrix?. Here is the scenario, I have a matrix of size 3 x 2 then someone wants to use use my program and he has a file with say matrix of size of 8 x 10...the program should handle any matrix size.

Separate Headers From Source.

by triumphost at 23:49 PM, 05/12/2012

Is it necessary to seperate the headers from the source?

For example I don't know why but I love to do:

//Foo.H

class Foo
{
    Foo(){}
    ~Foo(){}

    void Func()
    {
       //.........
       //.........
    }

    void Func2()
    {
        //........
        //........
    }

};

Instead of doing:

//Foo.H
class Foo
{
   Foo();
   ~Foo();

   void Func();
   void Func2();
};

//Foo.cpp
Foo::Foo()
{
  //.....
}

Foo::~Foo()
{
   //......
}

Foo::void Func()
{
   //.....
}

Foo::void Func2()
{
    //....
}

The second example which Hate to do seems like so much more work. Not only that but I'd have to constantly switch back and forth between headers and sources to see whats declared where or what contains what. But now I'm looking up all my habbits to see if they cause performance degradation and I've read the first one does whereas the second doesn't :S

I'm also reading that if i put my definitions inside the class, it's automatically inlined and that if I put the inline keyword in there then it's even worse :S Should I just leave them in there as inline and if not then why? Is there a way to define them inside the class and NOT be inlined?

Is this true? Am I actually doing something bad? I'm being told to never put the definitions in a header.. Only declarations.. Apparently it slows down compile time and slows down my program which is what I read at stack overflow from someone asking a similar question. I use header guards by the way.

I just really don't like having that many unneccesary files when I can just include my header with everything in there already..
So is it bad? Also why should a coder use the scope operator like that instead of putting it all inside the class? Is there an advantage such as performance/compile time or is it just style? C# doesn't seem to care whether or not everything is in one file..

Windows Console

by Labdabeta at 22:38 PM, 05/12/2012

I used to use a tutorial for windows console API, but the website was taken down :(. So now I need to ask how to do these things (which ALL were included on the website) in the console with windows API:

  • Mouse events (clicks and unclicks)
  • Cursor seeking (to any x/y coordinate)
  • Colour changing
  • Keyboard events (specifically arrow keys)

ofstream problem, not writing

by jakezcop at 21:56 PM, 05/12/2012

int Finish()//outputs stored values to file
{
    ofstream walletfile;
    walletfile.open("C:/accounts/wallet.acnt", ios::trunc);
    walletfile << wallet;
    walletfile.close();
    ofstream accountfile;
    accountfile.open("C:/accounts/account.acnt", ios::trunc);
    accountfile << account;
    accountfile.close();
    ofstream savingsfile;
    savingsfile.open("C:/accounts/savings.acnt", ios::trunc);
    savingsfile << savings;
    savingsfile.close();
    return 0;
   }

I am a brand new programmer, just learning from the web, i wrote this function as part of an accounting program to write stored values to an output file, the program compiles, and runs without any problems, but when i activate this function from within the program nothing happens, when i retrieve the values from the file, they are exactly the same as the last time i drew from the file. HELP!

Creating an IDE or Syntax highlighter.

by triumphost at 21:47 PM, 05/12/2012

I want to start developing an IDE or at least a Syntax highlighter into my program. Atm it's a simple text editor with basic copy paste functions.

How does Notepad++ do it? Is there a way I can integrate that into my own program? If not then I'll write it on my own. Also how does codeblocks compile our programs. I read that VC++ took 17 years to be created so how come codeblocks is so new and yet it compiles sourcecode :S

Also if codeblocks is using a backend compiler can I use that same thing in my program or is it going to take me years too?

Word comparison - Vectors /Getopt

by anonymous1987 at 21:36 PM, 05/12/2012

Please Help!!!

My understanding of getopt is very limited.
I do however realise that argv[0] is the exe file, argv[1] is the option, argv[2] is the word to compare and argv[3] is the dictionary or document I want to search(file .txt).
I'm trying to set a pointer to the dictionary and then iterate through it to see if there is a match with the argv[2] (input word) to the text file, and if there is a match out put the argv[2] word.
Below is my current code that has errors
main.cpp:61: error: no match for 'operator==' in 'list == (argv + 12u)'
main.cpp:64: error: no match for 'operator
' in '*list'
Any help would be greatly appreciated.

#include <cstdlib>
#include <unistd.h>
#include <vector>
#include <iostream>
#include <string>
#include <iterator>

using namespace std;

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

    enum {
        WHOLE, PREFIX, SUFFIX, ANYWHERE, EMBEDDED
    } mode = WHOLE;
    bool jumble = false;
    bool ignore_case = false;
    bool invert = false;
    string length = "0,0";
    int c;
    string input;
    vector <string> list;
    vector <string>::iterator i;

    while ((c = getopt(argc, argv, ":wpsaejivn:")) != -1) {
        switch (c) {
            case 'w': mode = WHOLE;
                break;
            case 'p': mode = PREFIX;
                break;
            case 's': mode = SUFFIX;
                break;
            case 'a': mode = ANYWHERE;
                break;
            case 'e': mode = EMBEDDED;
                break;
            case 'j': jumble = true;
                break;
            case 'i': ignore_case = true;
                break;
            case 'v': invert = true;
                break;
            case 'n': length = optarg;
                break;
            default: WHOLE;
                break;
        }
    }
    argc -= optind;
    argv += optind;

    switch (mode) {
        case WHOLE:
            while(argc != -1){
                list == argv[3];
                for(i == list.begin(); i != list.end(); i++)
                if(argv[1] == argv[3]){
                    cout << *list << endl;
                }else cout << "Did not work again" << endl;
            }                                  
    }
    return 0;
}

Netbeans

by Garrett85 at 18:25 PM, 05/12/2012

I just downloaded netbeans and when I went to start a C++ project I was told that Netbeans couldn't find a C++ compiler. When I use to play around witt MS Visual C++ I never ran into a problem like this, Can anyone tell me what's up and what I can do about it? Also, though I want to learn to program I might as well learn a language that can get me a job. What is the beast language out there to get you hired? Thanks again.

Keno Fun!

by Clinton Portis at 17:36 PM, 05/12/2012

have fun with this game o' keno! post here with your highest winnings

Trouble modifying a dynamically allocated array

by binningen at 14:39 PM, 05/12/2012

Hi,

I'm trying to write a function that enlarges a dynamically allocated array, but I am having some trouble doing so. Here's my code:

void enlargeArray(int *oldArr, int arraySize) 
{
   //oldArr is a dynamically allocated array

   int *newArr = new int[arraySize*2]; 

   //copy the elements from oldArr into newArr

   delete oldArr[]; 

   oldArr = newArr; 
}

However, although newArr gets created correctly, when I examine the contents of oldArr in my main function (where I call enlargeArray from), oldArr is unchanged. Does anyone have any tips for how to modify oldArr itself? Thank you.

help matrix

by rahulraj9 at 10:39 AM, 05/12/2012

matrix operation

please help me coding this in c++:
- Inverse matrices.
- Calculate matrix determinant.
- Set a row or a column of the matrix to a certain value.
- Calculate performance (time and memory taken by each algorithm).

DERIVATIVES(1ST&2ND) OF POLYNOMIAL FUNCTIONS

by nitinmbhanu at 08:35 AM, 05/12/2012

//PROGRAM TO FIND DERIVATIVE(FIRST AND SECOND)OF POLYNOMIAL FUNCTIONS
#include<iostream.h>
#include<conio.h>

void main()
{
    int i,d,coeff[100],degree[100];
    clrscr();
    cout<<"\nEnter the degree of the polynomial       : ";
    cin>>d;
    for(i=d;i>=0;i--)
    {     if(i>1)
          {
        degree[i]=i;
        cout<<"\nEnter the coefficient of x^"<<degree[i]<<" (with sign) : ";
        cin>>coeff[i];
          }
          else if(i==1)
          {
        degree[i]=i;
        cout<<"\nEnter the coefficient of x (with sign)   : ";
        cin>>coeff[i];
          }
          else
          {
        degree[0]=0;
        cout<<"\nEnter the constant term (if any)         : ";
        cin>>coeff[0];
          }
    }
    clrscr();
    cout<<"\n Entered polynomial function   , f (x)=";
    for(i=d;i>=0;i--)
    {
     if(coeff[i]>0&&degree[i]!=1)
     {
     if(degree[i])
     cout<<"+"<<coeff[i]<<"x^"<<degree[i];
     else
     cout<<"+"<<coeff[0];
     }
     else if(coeff[i]<0&&degree[i]!=1)
     {
     if(degree[i])
     cout<<coeff[i]<<"x^"<<degree[i];
     else
     cout<<coeff[0];
     }
     else if(coeff[i]!=0&&degree[i]==1)
     {
      if(coeff[i]>0)
      cout<<"+"<<coeff[i]<<"x";
      else
      cout<<coeff[i]<<"x";
     }
    }
    getch();
    for(i=d;i>=0;i--)
    {
     coeff[i]*=degree[i];
     degree[i]-=1;
    }
    cout<<"\n First derivative of function  , f'(x)=";
    for(i=d;i>=0;i--)
    {
     if(coeff[i]>0&&degree[i]!=1)
     {
     if(degree[i])
     cout<<"+"<<coeff[i]<<"x^"<<degree[i];
     else
     cout<<"+"<<coeff[i];
     }
     else if(coeff[i]<0&&degree[i]!=1)
     {
     if(degree[i])
     cout<<coeff[i]<<"x^"<<degree[i];
     else
     cout<<coeff[i];
     }
     else if(coeff[i]!=0&&degree[i]==1)
     {
      if(coeff[i]>0)
      cout<<"+"<<coeff[i]<<"x";
      else
      cout<<coeff[i]<<"x";
     }
    }
        getch();
    for(i=d;i>=0;i--)
    {
     coeff[i]*=degree[i];
     degree[i]-=1;
    }
    cout<<"\n Second derivative of function , f\"(x)=";
    for(i=d;i>=0;i--)
    {
     if(coeff[i]>0&&degree[i]!=1)
     {
     if(degree[i])
     cout<<"+"<<coeff[i]<<"x^"<<degree[i];
     else
     cout<<"+"<<coeff[i];
     }
     else if(coeff[i]<0&&degree[i]!=1)
     {
     if(degree[i])
     cout<<coeff[i]<<"x^"<<degree[i];
     else
     cout<<coeff[i];
     }
     else if(coeff[i]!=0&&degree[i]==1)
     {
      if(coeff[i]>0)
      cout<<"+"<<coeff[i]<<"x";
      else
      cout<<coeff[i]<<"x";
     }
    }
    getch();
}

Delete Node(or item) from a Linked-List

by BryantFury at 07:24 AM, 05/12/2012

Hi ive made a code does the following:

  1. user makes a list of items
  2. user adds more items to the list
  3. list is displayed

it uses Linked-Lists.
here is the code

#include <iostream>
using namespace std;

struct vote
{
       char product[10];
       vote *votePtr;
       };

void addNodes(vote *&startPtr,vote *&current, int total)
{
     cout<<"enter number of products to add to list:  ";
    cin>>total;
{
 vote *temp, *temp2;
 for(int i=0;i<total;i++)
 {      
         temp=new vote;
         cout<<"enter product name:";
         cin>>temp->product;


         temp->votePtr=NULL;
         if(startPtr==NULL)
         {
         startPtr=temp;
         current=startPtr;
         }
         else
         {
             temp2=startPtr;
             while(temp2->votePtr!=NULL)
             temp2=temp2->votePtr;
             temp2->votePtr=temp;
}
}
}
}

void insert(vote *&startPtr,vote *&current, int more)
{
     cout<<"How many more products you want to add? ";
    cin>>more;
{
 vote *temp, *temp2;
 for(int i=0;i<more;i++)
 {       
         temp=new vote;
         cout<<"enter product name:";
         cin>>temp->product;


         temp->votePtr=NULL;
         if(startPtr==NULL)
         {
         startPtr=temp;
         current=startPtr;
         }
         else
         {
             temp2=startPtr;
             while(temp2->votePtr!=NULL)
             temp2=temp2->votePtr;
             temp2->votePtr=temp;
}
}
}
}

void displayList(vote *&startPtr)
{
vote *yes;
yes=startPtr;
cout<<"RESULTS"<<endl;
while(yes!=NULL)
{
cout<<yes->product<<"  "<<endl;
yes=yes->votePtr;
}
}

void del()
{

 }

int main() {
    vote *startPtr=NULL;
    vote *current;
    int total=0;
    int more=0;

    addNodes(startPtr,current,total);  
    insert(startPtr,current,more);  
    del();  
    displayList(startPtr);

    system("pause");
    return 0;
}

i left out del for delete. the user should also be able to delete an item they previously added so it wont be displayed at the end. i am confused on how i would go about this etc. everything else works.
any help is much appreciated.

Which project to choose: Blackjack/checkers. Dealine: one week

by postbagoblivion at 03:47 AM, 05/12/2012

I am familiar with loops, functions, recursions, (though I have praticed some questions, it is troubling to get the hang of it completely), passing by value, reference and ofcourse pointers. I can work with arrays and 2d arrays.

This is my second project. My first project was hangman. My sir wasn't impressed if he did approve of what I made. This time, I wish to do better. I am willing to work harder but this project marks means alot. I want to ask you, is blackjack a better option to make my c++ project or checkers? I prefer checkers but I don't want to make the wrong descicion and get stuck because this time the deadline is quite near.

Appreciate your help.

c++ newbie, maybe template class related

by mayapower at 03:01 AM, 05/12/2012

Hi,

I am trying to create a programe like this:

n1 = NAttrib()
n2 = NAttrib()
out = NAttrib()

NAttrib class can be considered as general purpose attribute.

f1 = FloatAttrib(1.0)
f2 = FloatAttrib(2.0)

FloatAttribute class is like float type but with some extra spices. It has operator overloading functions such as add, multiply etc.

c1 = ComplexAttrib(arguments)
c2 = ComplexAttrib(arguments)

ComplexAttrib is a custom data type. It has operator overloading functions such as add, multiply etc.

n1.Set(f1)
n2.Set(f2)

Here we are setting FloatAttribute instances in our general purpose attribute.

out = n1 + n2

This should call add operator function defined in FloatAttribute class & out should become FloatAttribute

n1.Set(c1)
n2.Set(c2)

Here we are setting ComplexAttribute instances in our general purpose attribute.

out = n1 + n2

This should call add operator function defined in ComplexAttribute class & out should become ComplexAttribute

I am reading couple of books and also googling but still I am not sure how do I implement.
How to create NAttrib, FloatAttribute and ComplexAttribute class?

I am not sure but Template Class could be a solution?

Cheers

matrix operation

by samar11 at 03:01 AM, 05/12/2012

please help me coding this in c++:
 Inverse matrices.
 Calculate matrix determinant.
 Set a row or a column of the matrix to a certain value.
 Calculate performance (time and memory taken by each algorithm).

Display numbers from Linked List

by BryantFury at 02:19 AM, 05/12/2012

hi im currently learning about linked list. Ive created a code which is supposed to let you type some numbers, then display them. i did this mostly by using information on the internet(code examples) and such. Hence there are obvious mistakes a bits i do not understand. Here is my code:

#include <iostream>
using namespace std;

struct nodeType {
    int info;
    nodeType *link;
};
nodeType *head = NULL;

nodeType* buildListForward()
{
  nodeType *first,*newNode, *last;
  int num;
  cout<<"enter numbers";
  cin >>num;
  first=NULL;
  while(num!=-1)
  {
    newNode = new nodeType;     
    newNode->info =num;
    newNode->link = NULL;
    if(first==NULL)            
    {
    first = newNode;
    last= newNode;
    }
    else
    {
      last->link = newNode;
      last = newNode;
    }
    cin>>num;
   }
   return first;
}

void display() {
    struct nodeType *list = head;
    while(list) {
        cout << list->info <<" ";
        list = list->link;
    }
    cout << endl;
}

int main() {
    buildListForward();
    display();
    system("pause");
    return 0;
}

My question is, when i run the code i can type in the numbers until i type -1. it is then supposed to display what i typed. but it does not?

any help is greatly appreciated.

Using Single LinkedList for ShoppingList

by AlvinLiu at 17:46 PM, 05/11/2012

#include <string>
#include <cstdlib>

typedef enum {Dominion, Sobeys, Shoppers, Walmart} Store;

using namespace std;

class Item
{
private:
   // name of the item (non-empty string)
   string name;

   // number of dollars in price of item
   int dollars;

   // number of cents in price of item
   int cents;

   // store where item is sold
   Store whereToBuy;

   // number of items to buy
   int numToBuy;

public:

   // Default constructor for Item class.  Should set all fields to 0.
   Item();

   // Constructor for Item class
   Item(string name, int dollars, int cents, Store whereToBuy, int numtoBuy);

   // Returns the name of the item
   string getName();

   // Returns the cost of the item in dollars
   // Postcondition: dollars' >= 0
   //                cents' >= 0
   //                (dollars' > 0) or (cents' > 0)
   void getCost(int* dollars, int* cents);

   // Returns the store where the item is sold
   Store getStore();

   // Returns the quantity of the item to buyd
   int getNumToBuy();

   // Sets the name of the item
   // Precondition: name should be a non-empty string
   void setName(string name);

   // Sets the cost of the item in dollars
   // Precondition: (dollars >= 0)
   //               (cents >= 0)
   //               (dollars > 0) or (cents > 0)
   void setCost(int dollars, int cents);

   // Sets the store where the item is sold
   void setStore(Store store);

   // Sets the quantity of the item we want to buy
   // Precondition: numToBuy > 0
   void setNumToBuy(int numToBuy);
};

class ShoppingListNode
{
private:
    Item thisItem;
    ShoppingListNode* next;
public:
    ShoppingListNode(Item item)
    {
        thisItem = item;
        next = NULL;
    }
    ShoppingListNode(Item item, ShoppingListNode* nextNode)
    {
        thisItem = item;
        next = nextNode;
    }

};


class ShoppingList
{
private:
    ShoppingListNode* headNode;
public:

   // Creates an empty shopping list
   ShoppingList();

   // Constructor for a shopping list.
   // Precondition: items should point to an array of length numItems
   // Postcondition: After constructor is run, it should consist of numItem nodes with the items in the list the same as those in
   // the input array items and in that order.
   ShoppingList(Item* items, int numItems);

   // Constructor for a shopping list
   // Postcondition: (headNode->thisItem)' = item
   //                (headNode->next)' = restOfList
   ShoppingList(Item item, ShoppingListNode* restOfList);

   // Prints the names and prices of the items on the shopping list in
   // non-decreasing order of price per unit
   // Items should be printed out one per line - name first followed by a tab and then the price in the format $x.yz,
   // where x is the price in dollars, and yz is the price in cents (y and z are two decimal digits, and either or both may be 0).
   void printInOrder();

   // Returns the total cost of all items in the shopping list. Make sure that the individual price of each item in the list is multiplied by the
   // quantity of the item being purchased as given in the numToBuy field.
   // Postcondition: *dollars' >= 0
   //                *cents' >= 0
   //                *cents' < 100
   //                *dollars' = thisItem.dollars
   //                *cents' = thisItem.cents
   void getTotalCost(int* dollars, int* cents);

   // Adds item to the shopping list
   // Postcondition: If an item with the same name, location and price is already present in the list,
   // then the numToBuy field of the item in the list is incremented appropriately
   // Otherwise item is added as a fresh node to the list.
   bool addItem(Item item);

   // Removes item from the shopping list
   // Postcondition:  item is not present in the list after function execution
   // result is true if item was successfully removed
   // result is false if it wasn't in the list to begin with.
   bool removeItem(Item item);

   // Postcondition: result is true if the shopping list is empty and false otherwise.
   bool isEmpty();

   // Returns the number of stores where items have to be purchased from.
   // Postcondition: result >= 0
   int numStores();
};

This is .h file.

And following this is my cpp file . Please help me to resolve the printInOrder function, I have problems for reading the contents of everyNode, because the headNode->thisItem is not work, because the thisItem is in private.

Thank you

#include "ShoppingList.h"
#include <cassert>
#include <iostream>


Item::Item() {
    dollars = 0;
    cents = 0;
    numToBuy = 0;
}

Item::Item(string name, int dollars, int cents, Store whereToBuy, int numtoBuy) {
    name = name;
    dollars = dollars;
    cents = cents;
    whereToBuy = whereToBuy;
    numtoBuy = numToBuy;
}

string Item::getName() {
    return name;
}

void Item::getCost(int* dollars, int* cents) {
    if(*dollars == 0 && *cents == 0)
         cout << "error";
    cout << "$" + *dollars + '.' + *cents;
}

Store Item::getStore() {
    return whereToBuy;
}

int Item::getNumToBuy() {
    return numToBuy;
}

void Item::setName(string name) {
    assert(name!="");
    name = name;
}

void Item::setCost(int dollars, int cents) {
    double cost = 0.0;
    assert(dollars>=0 && cents>=0 && ((dollars > 0 && cents == 0) || (cents > 0 && dollars ==0)));
    cost = dollars + cents % 100;
}

void Item::setStore(Store store) {
    store = whereToBuy;
}

void Item::setNumToBuy(int numToBuy) {
    assert(numToBuy > 0);
    numToBuy = numToBuy;
}

ShoppingList::ShoppingList() {
    headNode = NULL;
}

//Constructor for a shopping list.
// Precondition: items should point to an array of length numItems
// Postcondition: After constructor is run, it should consist of numItem nodes with the items in the list the same as those in
// the input array items and in that order.  //
ShoppingList::ShoppingList(Item* items, int numItems) {
    ShoppingListNode* nextNode;
    headNode = new ShoppingListNode (*(items));
    for(int i = 0;i<numItems;i++){
        nextNode = new ShoppingListNode(*(items + i+1));
        nextNode = new ShoppingListNode (*(items+i),nextNode);
    }
}

// Constructor for a shopping list
// Postcondition: (headNode->thisItem)' = item
//                (headNode->next)' = restOfList
ShoppingList::ShoppingList(Item item, ShoppingListNode* restOfList) {
    headNode = new ShoppingListNode(item, restOfList);
}

// Prints the names and prices of the items on the shopping list in
// non-decreasing order of price per unit
// Items should be printed out one per line - name first followed by a tab and then the price in the format $x.yz,
// where x is the price in dollars, and yz is the price in cents (y and z are two decimal digits, and either or both may be 0).
void ShoppingList::printInOrder(){
     Item* item;
     ShoppingListNode* thisNode = headNode;
     ShoppingListNode* nextNode;
     int i = 0;
     //while(thisNode!= NULL){
        thisNode = new ShoppingListNode(*(item+i),nextNode);
        cout << (*(item+i)).getName();
        thisNode = nextNode;
     //}
}


bool ShoppingList::isEmpty() {
    if (headNode == NULL)
        return true;
    return false;
}

int ShoppingList::numStores(){
      Item tempI;
      Store tempS;
      int result1 = 0;
      int result2 = 0;
      int result3 = 0;
      int result4 = 0;
      ShoppingListNode* nextN = NULL;
      while(headNode != NULL){
          headNode = new ShoppingListNode(tempI,nextN);
          headNode = nextN;
          tempS = tempI.getStore();
          if(tempS == Dominion)
             result1 = 1;
          if(tempS == Sobeys)
             result2 = 1;
          if(tempS == Shoppers)
             result3 = 1;
          if(tempS == Walmart)
             result4 = 1;
      }
      return result1 + result2 + result3 + result4;
}


/************************Testing Main Function**************************/
int main() {
    int numItems;
    ShoppingList A;
    cout << "How many items do you want to buy? " << endl;
    cin >> numItems;
    Item* items;
    for(int i = 0;i<numItems;i++){
        *(items + i) = Item("Ada",1,2,Walmart,1);
        A(items,numItems);
    }
    A.printInOrder();
    return 0;
}

Struct with new operator

by JohnQ002 at 14:28 PM, 05/11/2012

I need to create a program that uses a structure that alocates memory with the new operator. The information must be saved in a file, then displayed. The problem I have is that the program saves only the first character of the words I enter. Could someone please help me make it work.

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <new>
using namespace std;

    FILE *f;
    struct dog {
        char  name;
        char  family;
        int   age;

                }list1, list2;

    int i,n,optie;


//File Dog 
int file_dog()
{   
    dog* plist; 

    cout << "  Point the number of dogs you want to enter\n" << endl;
    cin >> n;   

    plist = new (nothrow) dog[n];
    f=fopen("Dog.txt","w");
    if (plist == 0)
    cout << "Error: memory could not be allocated";
    else
    {
    for(i=0;i<n;i++)
     {
      cout << "  Enter the name of the dog       - " << endl;
      cin >> list1.name;
       fflush(stdin);
      cout << "  Enter the family of the dog     - "  << endl;
      cin >> list1.family;
       fflush(stdin);
      cout << "  Enter the age                   - " << endl;
      cin >> list1.age;
      fwrite(&list1,sizeof(list1),1,f);
      cout << endl;
     }
    cout << endl;
    fclose(f);
    delete []plist;
    }
    return 0;
}


int display_the_file_dog()
{   

    if((f=fopen("Dog.txt","r")) == NULL )
       {
         cout << "Error" << endl;
         exit(1);
       }

    cout << "          Date despre ciini" << endl;
    cout << "  ===================================" << endl;
    cout << "  | Nr |  Name |  Family  | Age | " << endl;
    cout << "  ===================================" << endl;
    i=1;
    fread(&list2,sizeof(list2),1,f);
    while(!feof(f))
    {
     cout << "    " << i++ << "       " << list2.name << "        " << list2.family << "        " << list2.age << endl;
     fread(&list2,sizeof(list2),1,f);
    cout << "  -----------------------------------" << endl;
    }
    cout << endl;
    fclose(f);
    return 0;
}


int main()
{   
    system("color 0");
    system("color f0");

    while (1)
     {
      cout << "                      -------------- M E N I U -------------" << endl;
      cout << "                      ----------- Choose an option ---------" << endl;
      cout << endl;
      cout << "                      | [1] - Create the file Dog          |" << endl;
      cout << "                      | [2] - Display the file Dog         |" << endl;
      cout << "                      | [3] - Exit the program             |" << endl;
      cout << "                      | ---------------------------------- |" << endl;
      cin >> optie; fflush(stdin);
    switch (optie)
     {
      case 1: file_dog(); break;
      case 2: display_the_file_dog(); break;
      case 3: exit(1);
      default: printf("Choose the right option\n"); break;
     } 
    }
    return 0;
}

Formatting Input/Output Files

by greencode at 13:44 PM, 05/11/2012

Hello,

I'm working on an assignment that requires me to do the following:

"A file contains 6 numbers per line and contains several records. Another file contains 3 numbers per line and several records. Write a program to input each of the numbers, find the highest number, the lowest number, their total and average. Output the numbers, the highest, lowest, total and average to another file."

Output.txt needs to look like this for each numbers per line:

1 2 3 4 5 6
Min: 1
Max: 6
Total: 21
Avg: 3

The problem I'm having with my code is instructing the computer to read the numbers per line, find the desired math results, output it the aforementioned format, and then repeat the algorithm in the next set of numbers. This is my code so far:

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main ()
{
    //Declaring variables
    ifstream inFile;
    ofstream outFile;
    int NumPerLine, num, count=0; 
    int sum=0, min=0, max=0, Total=0, Avg=0;
    int row=0, col=0, x, y;

    //Opening files
    inFile.open("input1.txt");
    outFile.open("output.txt");

    //************************
    //Code data manipulation
    //************************

    cout << "Processing data."
         << endl;

    //Read/Write Integer 
    inFile  >> NumPerLine;
    outFile << NumPerLine
            << endl;

    //While loop reads data  
    while (!inFile.eof())
    {
        inFile  >> num;
        outFile << num << "\t";
        sum = sum + num;
        count++;
    }//Needs to be solved: how do I run math processes(max,min,avg,total)w/ numbers
     //at end of line and THEN continue reading and repeating math processes for next line of numbers?

     /*Math processes 

     //Determining Average
       Avg = sum / count;
     //Determining Sum
       sum = num + sum;
     //Determining Max
       if(x>y)
                max=x;
                else
                max=y;
     //Determining Min
       if(x<y)
                min=x;
                else
                min=y;*/

     //************************
     //End of code data manip
     //************************

    //Close files
    inFile.close();
    outFile.close();

    return 0;

Please help! Thank you.

Windows Application using dev-c++

by iismitch55 at 13:36 PM, 05/11/2012

I have been messing around with making a windows application in Dev-C++ I wanted to make it in a single source file, rather than a project to see if it worked. It did, other than the fact that I got the windows app, AND a DOS prompt behind it. Is there anyway to remove the DOS prompt? I will include the code, so that you can see what I mean.

#include <windows.h>

/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

/*  Make the class name into a global variable  */
char szClassName[ ] = "WindowsApp";

int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil)

{
    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default color as the background of the window */
    wincl.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "Windows App",       /* Title Text */
           WS_SYSMENU,          /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           544,                 /* The programs width */
           375,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    /* Make the window visible on the screen */
    ShowWindow (hwnd, nFunsterStil);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}

#define ID_BTN 1
#define ID_TEXTBOX 2

static HWND hwndTextbox;

/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)                  /* handle the messages */
    {
        case WM_CREATE:
             {
                  hwndTextbox = CreateWindow(TEXT("EDIT"), TEXT("Type Here"),
                               WS_VISIBLE|WS_CHILD|WS_BORDER|ES_AUTOHSCROLL,
                               10,10,200,20,
                               hwnd, (HMENU) ID_TEXTBOX, NULL, NULL);
                  CreateWindow(TEXT("button"), TEXT("Click Me"),
                               WS_VISIBLE|WS_CHILD,
                               10,40,80,20,
                               hwnd, (HMENU) ID_BTN, NULL, NULL);
                               break;
             }
        case WM_COMMAND:
        {
             //action for button
             if (LOWORD(wParam) == ID_BTN)
             {
                //create variables
                int length = GetWindowTextLength(hwndTextbox) + 1;
                static char title[500] = "";
                GetWindowText(hwndTextbox,title,length);
                //MessageBox(hwnd, title, "Debug Box", MB_OK);
                // Creates a window displaying the text typed in the box.

                SetWindowText(hwnd, title);
             }
             break;
        }
        case WM_DESTROY:
            PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
            break;
        default:                      /* for messages that we don't deal with */
            return DefWindowProc (hwnd, message, wParam, lParam);
    }

    return 0;
}

stop runnig twice

by Carolin at 09:25 AM, 05/11/2012

hi guys....

i make a program with Dev-C++ ..... let say my program is already running now .... if i try to open it ... it show me a MessageBox or an output to tell me i can't run it when is already running

periodic table help shwing bgi error

by nitinmbhanu at 09:24 AM, 05/11/2012

#include<dos.h>
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<graphics.h>

int y;
int i;
struct element{   char name[20];
          int at_no;
          double at_wt,at_r,en,ion,density,mp,bp;
          char ato_wt[20],ato_r[20],eno[20];
          char iono[20],densityo[20],mpo[20],bpo[20];
          char crs[20];
          char sym[4];
          char earr[100];
         }E[118];
void numberfind(int);
void numrfind(int,int);
void massfind(double);
void namfind(char*);
void namlfind(char);
void massrfind(double,double);
void ionifind(double);
void ionirfind(double,double);
void enegfind(double);
void enegrfind(double,double);
void mepfind(double);
void meprfind(double,double);
void bepfind(double);
void beprfind(double,double);
void densefind(double);
void denserfind(double,double);
void elecfind(char*);
void radiusrfind(double,double);
void radiusfind(double);
void symbfind(char*);

int main(void)
{

   y:
    int gm,gd=DETECT;
    initgraph(&gd,&gm,"c:\\tc3\\bgi");


    for(int v=9,w=79;v<=170;v++,w++)
    {
    cleardevice();
    setcolor(random(15));
    settextstyle(4,0,200);
    outtextxy(v,w,"WELCOME TO MODERN PERIODIC TABLE");
    delay(100);
    }
    for(int q=0;q<5000;q++)
    {
     putpixel(random(700),random(500),random(16));
     delay(2);
    }
    setcolor(9);
    outtextxy(300,400,"PRESS ANY KEY TO  SEE THE PERIODIC TABLE...");
    getch();
    cleardevice();
    floodfill(0,0,0);
    setcolor(63);
    line(180,30,180,65);
    line(180,30,210,30);
    line(210,30,210,65);
    line(210,65,180,65);
    line(30,65,30,275);
    line(0,135,625,135);
    line(65,65,65,275);
    line(100,135,100,275);
    line(135,135,135,275);
    line(170,135,170,275);
    line(205,135,205,275);
    line(240,135,240,275);
    line(275,135,275,275);
    line(310,135,310,275);
    line(345,135,345,275);
    line(380,135,380,275);
    line(415,65,415,275);
    line(450,65,450,275);
    line(485,65,485,275);
    line(520,65,520,275);
    line(555,65,555,275);
    line(590,30,590,275);
    line(625,30,625,275);
    line(0,65,0,275);
    line(0,170,625,170);
    line(0,205,625,205);
    line(0,240,625,240);
    line(0,275,625,275);
    line(0,65,65,65);
    line(0,100,65,100);
    line(415,65,625,65);
    line(415,100,625,100);
    line(590,30,625,30);
    line(590,30,625,30);
    line(135,420,625,420);
    line(135,350,135,420);
    line(135,350,625,350);
    line(135,385,625,385);
    line(170,350,170,420);
    line(205,350,205,420);
    line(240,350,240,420);
    line(275,350,275,420);
    line(310,350,310,420);
    line(345,350,345,420);
    line(380,350,380,420);
    line(415,350,415,420);
    line(450,350,450,420);
    line(485,350,485,420);
    line(520,350,520,420);
    line(555,350,555,420);
    line(590,350,590,420);
    line(625,350,625,420);
    setcolor(58);
    line(0,65,0,275);
    line(0,65,65,65);
    line(65,65,65,275);
    line(65,275,0,275);
    setcolor(1);
    line(67,275,413,275);
    line(67,275,67,135);
    line(67,135,413,135);
    line(413,135,413,275);
    setcolor(3);
    line(415,275,415,65);
    line(415,275,625,275);
    line(625,275,625,30);
    line(590,65,415,65);
    line(625,30,590,30);
    line(590,30,590,65);
    setcolor(60);
    line(135,350,625,350);
    line(135,350,135,385);
    line(135,385,625,385);
    line(625,350,625,385);
    setcolor(61);
    line(625,387,625,420);
    line(625,420,135,420);
    line(135,420,135,387);
    line(135,387,625,387);
    setcolor(59);
    line(133,348,627,348);
    line(133,348,133,422);
    line(133,422,627,422);
    line(627,422,627,348);
    setcolor(58);
    settextstyle(9,0,0);
    outtextxy(190,35,"1");
    outtextxy(190,50,"H");
    setcolor(57);
    settextstyle(9,0,0);
    outtextxy(10,70,"3");
    outtextxy(10,105,"11");
    outtextxy(10,140,"19");
    outtextxy(10,175,"37");
    outtextxy(10,210,"55");
    outtextxy(10,245,"87");
    outtextxy(40,70,"4");
    outtextxy(40,105,"12");
    outtextxy(40,140,"20");
    outtextxy(40,175,"38");
    outtextxy(40,210,"56");
    outtextxy(40,245,"88");
    outtextxy(10,85,"Li");
    outtextxy(10,120,"Na");
    outtextxy(10,155,"K");
    outtextxy(10,190,"Rb");
    outtextxy(10,225,"Cs");
    outtextxy(10,260,"Fr");
    outtextxy(40,85,"Be");
    outtextxy(40,120,"Mg");
    outtextxy(40,155,"Ca");
    outtextxy(40,190,"Sr");
    outtextxy(40,225,"Ba");
    outtextxy(40,260,"Ra");
    setcolor(1);
    outtextxy(75,140,"21");
    outtextxy(75,175,"39");
    outtextxy(110,140,"22");
    outtextxy(110,175,"40");
    outtextxy(110,210,"72");
    outtextxy(110,245,"104");
    outtextxy(145,140,"23");
    outtextxy(145,175,"41");
    outtextxy(145,210,"73");
    outtextxy(145,245,"105");
    outtextxy(180,140,"24");
    outtextxy(180,175,"42");
    outtextxy(180,210,"74");
    outtextxy(180,245,"106");
    outtextxy(215,140,"25");
    outtextxy(215,175,"43");
    outtextxy(215,210,"75");
    outtextxy(215,245,"107");
    outtextxy(250,140,"26");
    outtextxy(250,175,"44");
    outtextxy(250,210,"76");
    outtextxy(250,245,"108");
    outtextxy(285,140,"27");
    outtextxy(285,175,"45");
    outtextxy(285,210,"77");
    outtextxy(285,245,"109");
    outtextxy(320,140,"28");
    outtextxy(320,175,"46");
    outtextxy(320,210,"78");
    outtextxy(315,245,"110");
    outtextxy(355,140,"29");
    outtextxy(355,175,"47");
    outtextxy(355,210,"79");
    outtextxy(350,245,"111");
    outtextxy(390,140,"30");
    outtextxy(390,175,"46");
    outtextxy(390,210,"80");
    outtextxy(385,245,"112");
    outtextxy(75,155,"Sc");
    outtextxy(75,190,"Y");
    outtextxy(110,155,"Ti");
    outtextxy(110,190,"Zr");
    outtextxy(110,225,"Hf");
    outtextxy(110,260,"Rf");
    outtextxy(145,155,"V");
    outtextxy(145,190,"Nb");
    outtextxy(145,225,"Ta");
    outtextxy(145,260,"Db");
    outtextxy(180,155,"Cr");
    outtextxy(180,190,"Mo");
    outtextxy(180,225,"W");
    outtextxy(180,260,"Sg");
    outtextxy(215,155,"Mn");
    outtextxy(215,190,"Tc");
    outtextxy(215,225,"Re");
    outtextxy(215,260,"Bh");
    outtextxy(250,155,"Fe");
    outtextxy(250,190,"Ru");
    outtextxy(250,225,"Os");
    outtextxy(250,260,"Hs");
    outtextxy(285,155,"Co");
    outtextxy(285,190,"Rh");
    outtextxy(285,225,"Ir");
    outtextxy(285,260,"Mt");
    outtextxy(320,155,"Ni");
    outtextxy(320,190,"Pd");
    outtextxy(320,225,"Pt");
    outtextxy(315,260,"Ds");
    outtextxy(355,155,"Cu");
    outtextxy(355,190,"Ag");
    outtextxy(355,225,"Au");
    outtextxy(350,260,"Rg");
    outtextxy(390,155,"Zn");
    outtextxy(390,190,"Cd");
    outtextxy(390,225,"Hg");
    outtextxy(385,260,"Cn");
    setcolor(57);
    outtextxy(425,140,"31");
    outtextxy(425,175,"49");
    outtextxy(425,210,"81");
    outtextxy(420,245,"113");
    outtextxy(425,105,"13");
    outtextxy(425,155,"Ga");
    outtextxy(425,190,"In");
    outtextxy(425,225,"Ti");
    outtextxy(420,260,"Uut");
    outtextxy(425,120,"Al");
    setcolor(58);
    outtextxy(425,85,"B");
    setcolor(58);
    outtextxy(460,85,"C");
    setcolor(4);
    outtextxy(460,120,"Si");
    outtextxy(460,155,"Ge");
    setcolor(57);
    outtextxy(460,190,"Sn");
    outtextxy(460,225,"Pb");
    outtextxy(455,260,"Uuq");
    setcolor(58);
    outtextxy(495,85,"N");
    outtextxy(495,120,"P");
    setcolor(4);
    outtextxy(495,155,"As");
    outtextxy(495,190,"Sb");
    setcolor(57);
    outtextxy(495,225,"Bi");
    outtextxy(490,260,"Uup");
    setcolor(58);
    outtextxy(530,85,"O");
    outtextxy(530,120,"S");
    outtextxy(530,155,"Se");
    setcolor(4);
    outtextxy(530,190,"Te");
    outtextxy(530,225,"Po");
    setcolor(57);
    outtextxy(525,260,"Uuh");
    setcolor(58);
    outtextxy(565,85,"F");
    outtextxy(565,120,"Cl");
    outtextxy(565,155,"Br");
    outtextxy(565,190,"I");
    setcolor(4);
    outtextxy(565,225,"At");
    setcolor(57);
    outtextxy(560,260,"Uus");
    setcolor(5);
    outtextxy(600,35,"2");
    outtextxy(600,70,"10");
    outtextxy(600,105,"18");
    outtextxy(600,140,"36");
    outtextxy(600,175,"54");
    outtextxy(600,210,"86");
    outtextxy(600,245,"118");
    outtextxy(600,50,"He");
    outtextxy(600,85,"Ne");
    outtextxy(600,120,"Ar");
    outtextxy(600,155,"Kr");
    outtextxy(600,190,"Xe");
    outtextxy(600,225,"Rn");
    outtextxy(600,260,"Uuo");
    setcolor(1);
    settextstyle(0,0,2);
    outtextxy(165,5,"PERIODIC TABLE");
    outtextxy(163,8,"______________");
    settextstyle(3,0,0);
    setcolor(60);
    outtextxy(75,225,"La");
    outtextxy(145,375,"Ce");
    outtextxy(180,375,"Pr");
    outtextxy(215,375,"Nd");
    outtextxy(250,375,"Pm");
    outtextxy(285,375,"Sm");
    outtextxy(320,375,"Eu");
    outtextxy(355,375,"Gd");
    outtextxy(390,375,"Tb");
    outtextxy(425,375,"Dy");
    outtextxy(460,375,"Ho");
    outtextxy(495,375,"Er");
    outtextxy(530,375,"Tm");
    outtextxy(565,375,"Yb");
    outtextxy(600,375,"Lu");
    outtextxy(145,360,"58");
    outtextxy(180,360,"59");
    outtextxy(215,360,"60");
    outtextxy(250,360,"61");
    outtextxy(285,360,"62");
    outtextxy(320,360,"63");
    outtextxy(355,360,"64");
    outtextxy(390,360,"65");
    outtextxy(425,360,"66");
    outtextxy(460,360,"67");
    outtextxy(495,360,"68");
    outtextxy(530,360,"69");
    outtextxy(565,360,"70");
    outtextxy(600,360,"71");
    outtextxy(75,210,"57");
    setcolor(61);
    outtextxy(145,395,"90");
    outtextxy(180,395,"91");
    outtextxy(215,395,"92");
    outtextxy(250,395,"93");
    outtextxy(285,395,"94");
    outtextxy(320,395,"95");
    outtextxy(355,395,"96");
    outtextxy(390,395,"97");
    outtextxy(425,395,"98");
    outtextxy(460,395,"99");
    outtextxy(495,395,"100");
    outtextxy(530,395,"101");
    outtextxy(565,395,"102");
    outtextxy(600,395,"103");
    outtextxy(75,245,"89");
    outtextxy(75,260,"Ac");
    outtextxy(145,410,"Th");
    outtextxy(180,410,"Pa");
    outtextxy(215,410,"U");
    outtextxy(250,410,"Np");
    outtextxy(285,410,"Pu");
    outtextxy(320,410,"Am");
    outtextxy(355,410,"Cm");
    outtextxy(390,410,"Bk");
    outtextxy(425,410,"Cf");
    outtextxy(460,410,"Es");
    outtextxy(495,410,"Fm");
    outtextxy(530,410,"Md");
    outtextxy(565,410,"No");
    outtextxy(600,410,"Lr");
    setcolor(60);
    outtextxy(20,365,"Lanthanoides--");
    setcolor(61);
    outtextxy(20,400,"Actinoides----");
    setcolor(59);
    outtextxy(135,330,"|----------------------f-block Elements----------------------|");
    setcolor(1);
    outtextxy(65,120,"|-------------d-block Elements-------------|");
    setcolor(3);
    outtextxy(412,15,"|-----p-block Elements----|");
    outtextxy(0,50,"|--------|");
    setcolor(2);
    outtextxy(0,35,"s-block Elements");
    setcolor(58);
    outtextxy(425,70,"5");
    outtextxy(460,70,"6");
    setcolor(4);
    outtextxy(460,105,"14");
    outtextxy(460,140,"32");
    outtextxy(495,140,"33");
    outtextxy(495,175,"51");
    outtextxy(530,175,"52");
    outtextxy(530,210,"84");
    setcolor(57);
    outtextxy(460,175,"50");
    outtextxy(460,210,"82");
    outtextxy(455,245,"114");
    setcolor(58);
    outtextxy(495,70,"7");
    outtextxy(495,105,"15");
    outtextxy(530,70,"8");
    outtextxy(530,105,"16");
    outtextxy(530,140,"34") ;
    outtextxy(565,70,"9");
    outtextxy(565,105,"17");
    outtextxy(565,140,"35");
    outtextxy(565,175,"53");
    setcolor(57);
    outtextxy(495,210,"83");
    outtextxy(490,245,"115");
    outtextxy(525,245,"116");
    outtextxy(560,245,"117");
    setcolor(4);
    outtextxy(565,210,"85");
    outtextxy(400,450,"PRESS ANY KEY TO CONTINUE...");
    getch();
    closegraph();
   restorecrtmode();

    int m=63;
    clrscr();
    int ch=0;
    q:
    clrscr();
    textcolor(m);
    cout<<"\n\n\n\n\n\n\n\n\n\n\t\t\t\t";
    cprintf("%s","This is what you can do...");
    cout<<"\n\n\n\n\t\t\t\t";
    cprintf("%s","1. Show periodic table");
    cout<<"\n\t\t\t\t";
    cprintf("%s","2. Find elements");
    cout<<"\n\t\t\t\t";
    cprintf("%s","3. Options");
    cout<<"\n\t\t\t\t";
    cprintf("%s","4. Exit");
    cout<<"\n\t\t\t\t";
    cprintf("%s","Enter the choice : ");
    cin>>ch;
    switch(ch)
    {
    case 1:  setgraphmode(getgraphmode());
         goto y;
    case 2:
           w:

           clrscr();
           int find;
           cout<<"\n\n\n\n\t\t\t\t1.Find an element";
           cout<<"\n\t\t\t\t2.Find elements in a range";
           cout<<"\n\t\t\t\t3.Go to previous menu";
           cout<<"\n\t\t\t\t4.Exit";
           cout<<"\n\t\t\t\tEnter your choice : ";
           cin>>find;
           clrscr();
           switch(find)
           {
        case 1:
               e:
               clrscr();
               int find1;
               cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY";
               cout<<"\n\t\t\t\t\t 1. Atomic number";
               cout<<"\n\t\t\t\t\t 2. Atomic weight";
               cout<<"\n\t\t\t\t\t 3. Name";
               cout<<"\n\t\t\t\t\t 4. Atomic radius";
               cout<<"\n\t\t\t\t\t 5. Electronegativity";
               cout<<"\n\t\t\t\t\t 6. Ionisation enthalpy";
               cout<<"\n\t\t\t\t\t 7. Electron Arrangement";
               cout<<"\n\t\t\t\t\t 8. Melting point";
               cout<<"\n\t\t\t\t\t 9. Boiling point";
               cout<<"\n\t\t\t\t\t10. Density";
               cout<<"\n\t\t\t\t\t11. Symbol";
               cout<<"\n\t\t\t\t\t12. Go to previous menu";
               cout<<"\n\t\t\t\t\t13. Exit";
               cout<<"\n\t\t\t\t\t Enter the choice : ";
               cin>>find1;
               clrscr();
               switch(find1)
               {
            case 1 :  int num;
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY ATOMIC NUMBER";
                  cout<<"\n\n\n\n\t\t\t\tEnter the number : ";
                  cin>>num;
                  numberfind(num);
                  goto e;
            case 2 :  double mass;
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY ATOMIC WEIGHT";
                  cout<<"\n\n\n\n\t\t\t\tEnter the weight : ";
                  cin>>mass;
                  massfind(mass);
                  goto e;
            case 3 :  char nam[100];
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY NAME";
                  cout<<"\n\n\n\n\t\t\t\tEnter the name : ";
                  gets(nam);
                  namfind(nam);
                  goto e;
            case 4 :  double radius;
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY ATOMIC RADIUS";
                  cout<<"\n\n\n\n\t\t\t\tEnter the atomic radius : ";
                  cin>>radius;
                  radiusfind(radius);
                  goto e;
            case 6 :  double ioni;
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY IONISATION ENTHALPY";
                  cout<<"\n\n\n\n\t\t\t\tEnter the ionisation enthalpy : ";
                  cin>>ioni;
                  ionifind(ioni);
                  goto e;
            case 7 :  char elec[100];
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY ELECTRON ARRANGEMENT";
                  cout<<"\n\n\n\n\t\t\t\tEnter the electron arrangement : ";
                  gets(elec);
                  elecfind(elec);
                  goto e;
            case 8 :  double mep;
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY MELTING POINT";
                  cout<<"\n\n\n\n\t\t\t\tEnter the melting point : ";
                  cin>>mep;
                  mepfind(mep);
                  goto e;
            case 9 :  double bep;
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY BOILING POINT";
                  cout<<"\n\n\n\n\t\t\t\tEnter the boiling point : ";
                  cin>>bep;
                  bepfind(bep);
                  goto e;
            case 10:  double dense;
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY DENSITY";
                  cout<<"\n\n\n\n\t\t\t\tEnter the density : ";
                  cin>>dense;
                  densefind(dense);
                  goto e;
            case 11:  char symb[9];
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY SYMBOL";
                  cout<<"\n\n\n\n\t\t\t\tEnter the symbol : ";
                  gets(symb);
                  symbfind(symb);
                  goto e;
            case  5:  double eneg;
                  cout<<"\n\n\n\n\t\t\t\tFIND AN ELEMENT BY ELECTRONEGATIVITY";
                  cout<<"\n\n\n\n\t\t\t\tEnter the electronegativity : ";
                  cin>>eneg;
                  enegfind(eneg);
                  goto e;
            case 12:  goto w;
            case 13:  exit(0);
            default:  cout<<"\nINVALID CHOICE !!!";
                  goto e;
               }

        case 2:
               r:

               clrscr();
               int find2;
               cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY";
               cout<<"\n\t\t\t\t\t 1. Atomic number";
               cout<<"\n\t\t\t\t\t 2. Atomic weight";
               cout<<"\n\t\t\t\t\t 3. Starting letter";
               cout<<"\n\t\t\t\t\t 4. Atomic radius";
               cout<<"\n\t\t\t\t\t 5. Electronegativity";
               cout<<"\n\t\t\t\t\t 6. Ionisation enthalpy";
               cout<<"\n\t\t\t\t\t 7. Melting point";
               cout<<"\n\t\t\t\t\t 8. Boiling point";
               cout<<"\n\t\t\t\t\t 9. Density";
               cout<<"\n\t\t\t\t\t10. Go to previous menu";
               cout<<"\n\t\t\t\t\t11. Exit";
               cout<<"\n\t\t\t\t\t Enter the choice : ";
               cin>>find2;
               clrscr();
               switch(find2)
               {
            case 1 :  int num1,num2;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY ATOMIC NUMBER";
                  cout<<"\n\n\n\n\t\t\t\tEnter the number 1 : ";
                  cin>>num1;
                  cout<<"\n\n\n\n\t\t\t\tEnter the number 2 : ";
                  cin>>num2;
                  numrfind(num1,num2);
                  goto r;
            case 2 :  double mass1,mass2;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY ATOMIC WEIGHT";
                  cout<<"\n\n\n\n\t\t\t\tEnter the weight 1 : ";
                  cin>>mass1;
                  cout<<"\n\n\n\n\t\t\t\tEnter the weight 2 : ";
                  cin>>mass2;
                  massrfind(mass1,mass2);
                  goto r;
            case 3 :  char naml;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY STARTING LETTER";
                  cout<<"\n\n\n\n\t\t\t\tEnter the starting letter : ";
                  cin>>naml;
                  namlfind(naml);
                  goto r;
            case 4 :  double radius1,radius2;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY ATOMIC RADIUS";
                  cout<<"\n\n\n\n\t\t\t\tEnter the atomic radius 1 : ";
                  cin>>radius1;
                  cout<<"\n\n\n\n\t\t\t\tEnter the atomic radius 2 : ";
                  cin>>radius2;
                  radiusrfind(radius1,radius2);
                  goto r;
            case 6 :  double ioni1,ioni2;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY IONISATION ENTHALPY";
                  cout<<"\n\n\n\n\t\t\t\tEnter the ionisation enthalpy 1 : ";
                  cin>>ioni1;
                  cout<<"\n\n\n\n\t\t\t\tEnter the ionisation enthalpy 2 : ";
                  cin>>ioni2;
                  ionirfind(ioni1,ioni2);
                  goto r;
            case 7 :  double mep1,mep2;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY MELTING POINT";
                  cout<<"\n\n\n\n\t\t\t\tEnter the melting point 1 : ";
                  cin>>mep1;
                  cout<<"\n\n\n\n\t\t\t\tEnter the melting point 2 : ";
                  cin>>mep2;
                  meprfind(mep1,mep2);
                  goto r;
            case 8 :  double bep1,bep2;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY BOILING POINT";
                  cout<<"\n\n\n\n\t\t\t\tEnter the boiling point 1 : ";
                  cin>>bep1;
                  cout<<"\n\n\n\n\t\t\t\tEnter the boiling point 2 : ";
                  cin>>bep2;
                  beprfind(bep1,bep2);
                  goto r;
            case  9:  double dense1,dense2;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY DENSITY";
                  cout<<"\n\n\n\n\t\t\t\tEnter the density 1 : ";
                  cin>>dense1;
                  cout<<"\n\n\n\n\t\t\t\tEnter the density 2 : ";
                  cin>>dense2;
                  denserfind(dense1,dense2);
                  goto r;
            case  5:  double eneg1,eneg2;
                  cout<<"\n\n\n\n\t\t\t\tFIND ELEMENTS IN A RANGE BY ELECTRONEGATIVITY";
                  cout<<"\n\n\n\n\t\t\t\tEnter the electronegativity 1 : ";
                  cin>>eneg1;
                  cout<<"\n\n\n\n\t\t\t\tEnter the electronegativity 2 : ";
                  cin>>eneg2;
                  enegrfind(eneg1,eneg2);
                  goto r;
            case 10:  goto e;
            case 11:  exit(0);
            default: cout<<"\nINVALID CHOICE !!!";
                 goto r;
               }

        case 3:goto q;
        case 4:exit(0);
           default:cout<<"\n INVALID CHOICE !!!";
               goto w;
           }

    case 3:clrscr();
           textattr(m);
           cout<<"\n\n\n\n\t\t\t\tChange display colour";
           cout<<"\n\t\t\t\tPress number key";
           for(int i=1;i<15;i++)
           {
        textattr(i);
        cout<<"\n\t\t\t\t";
        cprintf("%d",i);
           }
           cout<<"\n\n\n\n\t\t\t\tIF YOU KNOW OTHER COLOUR CODE YOU CAN ENTER IT";
           cout<<"\n\n\t\t\t\tENTER CHOICE : ";
           cin>>m;
           goto q;
    case 4:exit(0);
    }
 getch();
return 0;
}

void numberfind(int x)
{
clrscr();
strcpy(E[1].name,"Hydrogen");
strcpy(E[1].sym,"H");
E[1].at_no=1;
E[1].at_wt=1.00797;
strcpy(E[ 1].crs,"hcp/cubic");
E[1].at_r=46;
E[1].ion=13.598;
E[1].en=2.1;
E[1].density=0.08987;
E[1].mp=14.01;
E[1].bp=20.4;
strcpy(E[ 1].earr,"1s1");
strcpy(E[ 2].name,"Helium");
strcpy(E[ 2].sym,"He");
E[2].at_no=2;
E[2].at_wt=4.003;
strcpy(E[2].crs,"hcp/cubic");
E[2].at_r=176;
E[2].ion=24.587;
strcpy(E[ 2].eno,"NO DATA");
E[2].density=0.166;
E[2].mp=0.95;
E[2].bp=4.21;
strcpy(E[ 2].earr,"1s2");
strcpy(E[ 3].name,"Lithium");
strcpy(E[ 3].sym,"Li");
E[3].at_no=3;
E[3].at_wt=6.94;
strcpy(E[ 3].crs,"hcp/fcc/bcc");
E[3].at_r=152;
E[3].ion=5.392;
E[3].en=1.0;
E[3].density=534;
E[3].mp=452;
E[3].bp=1590;
strcpy(E[ 3].earr,"[He] 2s1");
strcpy(E[ 89].name,"Actinium");
strcpy(E[ 89].sym,"Ac");
E[89].at_no=89;
E[89].at_wt=227;
strcpy(E[ 89].crs,"fcc");
E[89].at_r=188;
E[89].ion=6.9;
E[89].en=1.1;
E[89].density=10100;
E[89].mp=1320;
E[89].bp=3470;
strcpy(E[ 89].earr,"[Rn] 6d1 7s2");
strcpy(E[ 13].name,"Aluminium");
strcpy(E[ 13].sym,"Al");
E[13].at_no=13;
E[13].at_wt=26.98;
strcpy(E[ 13].crs,"fcc");
E[13].at_r=142;
E[13].ion=5.986;
E[13].en=1.5;
E[13].density=2700;
E[13].mp=933.2;
E[13].bp=2740;
strcpy(E[ 13].earr,"[Ne] 3s2 3p1");
strcpy(E[ 4].name,"Beryllium");
strcpy(E[ 4].sym,"Be");
E[4].at_no=4;
E[4].at_wt=9.01;
strcpy(E[ 4].crs,"hcp/cubic");
E[4].at_r=112;
E[4].ion=9.322;
E[4].en=1.5;
E[4].density=1800;
E[4].mp=1550;
E[4].bp=3243;
strcpy(E[ 4].earr,"[He] 2s2");
strcpy(E[51].name,"Antimony");
strcpy(E[ 51].sym,"Sb");
E[51].at_no=51;
E[51].at_wt=121.75;
strcpy(E[ 51].crs,"rhombic");
E[51].at_r=145;
E[51].ion=8.641;
E[51].en=1.9;
E[51].density=6700;
E[51].mp=903.7;
E[51].bp=1650;
strcpy(E[ 51].earr,"[Xe] 4d10 5s2 5p3");
strcpy(E[ 18].name,"Argon");
strcpy(E[ 18].sym,"Ar");
E[18].at_no=18;
E[18].at_wt=39.95;
strcpy(E[ 18].crs,"fcc");
E[18].at_r=174;
E[18].ion=15.759;
strcpy(E[ 18].eno,"NO DATA");
E[18].density=1.66;
E[18].mp=83.7;
E[18].bp=87.4;
strcpy(E[ 18].earr,"[Ne] 3s2 3p6");
strcpy(E[ 33].name,"Arsenic");
strcpy(E[ 33].sym,"As");
E[33].at_no=33;
E[33].at_wt=74.92;
strcpy(E[ 33].crs,"rhombic");
E[33].at_r=125;
E[33].ion=9.81;
E[33].en=2.0;
E[33].density=5730;
E[33].mp=1090;
E[33].bp=886;
strcpy(E[ 33].earr,"[Ar] 3d10 4s2 4p3");
strcpy(E[ 85].name,"Astatine");
strcpy(E[ 85].sym,"At");
E[85].at_no=85;
E[85].at_wt=210;
strcpy(E[ 85].crs,"NO DATA");
E[85].at_r=150;
E[85].ion=9.5 ;
E[85].en=2.2;
strcpy(E[ 85].densityo,"NO DATA");
E[85].mp= 520;
E[85].bp= 623;
strcpy(E[ 85].earr,"[Xe] 4f14 5d10 6s2 6p5");
strcpy(E[ 56].name,"Barium");
strcpy(E[ 56].sym,"Ba");
E[56].at_no=56;
E[56].at_wt= 137.34;
strcpy(E[ 56].crs,"bcc");
E[56].at_r= 217;
E[56].ion= 5.212;
E[56].en= 0.9;
E[56].density=3600;
E[56].mp=1000;
E[56].bp=1910;
strcpy(E[ 56].earr,"[Xe] 6s2");
strcpy(E[ 83].name,"Bismuth");
strcpy(E[ 83].sym,"Bi");
E[83].at_no= 83;
E[ 83].at_wt= 208.98;
strcpy(E[ 83].crs,"rhombic");
E[83].at_r= 155;
E[83].ion= 7.289;
E[83].en= 1.9;
E[83].density=9800;
E[83].mp=544.4;
E[83].bp=1830;
strcpy(E[ 83].earr,"[Xe] 4f14 5d10 6s2 6p3");
strcpy(E[ 5].name,"Boron");
strcpy(E[ 5].sym,"B");
E[5].at_no= 5;
E[5].at_wt= 10.81;
strcpy(E[ 5].crs,"ortho");
E[5].at_r= 88;
E[5].ion= 8.289;
E[5].en= 2.0;
E[5].density=2500;
E[5].mp= 2600;
E[5].bp= 2820;
strcpy(E[ 5].earr,"[He] 2s2 2p1");
strcpy(E[ 35].name,"Bromine");
strcpy(E[ 35].sym,"Br");
E[35].at_no=35;
E[35].at_wt= 79.90;
strcpy(E[ 35].crs,"ortho");
E[35].at_r= 114;
E[35].ion=  11.814;
E[35].en=  2.8;
E[35].density= 3100;
E[35].mp=265.9;
E[35].bp= 331.9;
strcpy(E[ 35].earr,"[Ar] 3d10 4s2 4p5");
strcpy(E[ 48].name,"Cadmium");
strcpy(E[ 48].sym,"Cd");
E[48].at_no=48;
E[48].at_wt= 112.40;
strcpy(E[ 48].crs,"hcp");
E[48].at_r=148;
E[48].ion=8.993;
E[48].en= 1.7;
E[48].density=8650;
E[48].mp= 594.2;
E[48].bp= 1038;
strcpy(E[ 48].earr,"[Kr] 4d10 5s2");
strcpy(E[ 55].name,"Caesium");
strcpy(E[ 55].sym,"Cs");
E[55].at_no= 55;
E[55].at_wt= 132.90;
strcpy(E[ 55].crs,"bcc");
E[55].at_r= 262;
E[55].ion= 3.894;
E[55].en= 0.7;
E[55].density=1870;
E[55].mp= 301.6;
E[55].bp= 960;
strcpy(E[ 55].earr,"[Xe] 6s1");
strcpy(E[ 20].name,"Calcium");
strcpy(E[ 20].sym,"Ca");
E[20].at_no=20;
E[20].at_wt=40.08;
strcpy(E[ 20].crs,"fcc");
E[20].at_r=196;
E[20].ion= 6.113;
E[20].en= 1.0;
E[20].density=1540;
E[20].mp= 1120;
E[20].bp= 1760;
strcpy(E[ 20].earr,"[Ar] 4s2");
strcpy(E[ 6].name,"Carbon");
strcpy(E[ 6].sym,"C");
E[6].at_no= 6;
E[6].at_wt= 12.01;
strcpy(E[ 6].crs,"hex");
E[6].at_r= 77;
E[6].ion= 11.260;
E[6].en= 2.5;
E[6].density=2300;
E[6].mp= 3801;
E[6].bp= 5100;
strcpy(E[ 6].earr,"[He] 2s2 2p2");
strcpy(E[ 58].name,"Cerium");
strcpy(E[ 58].sym,"Ce");
E[58].at_no=58;
E[58].at_wt=140.12;
strcpy(E[ 58].crs,"fcc");
E[58].at_r= 183;
E[58].ion= 5.47;
E[58].en= 1.1;
E[58].density=6800;
E[58].mp= 1070;
E[58].bp= 3740;
strcpy(E[ 58].earr,"[Xe] 4f2 6s2");
strcpy(E[ 17].name,"Chlorine");
strcpy(E[ 17].sym,"Cl");
E[17].at_no= 17;
E[17].at_wt=35.45;
strcpy(E[17].crs,"tetra");
E[17].at_r= 91;
E[17].ion= 12.967;
E[17].en= 3.0;
E[17].density=3.21;
E[17].mp= 172.1;
E[17].bp= 238.5;
strcpy(E[ 17].earr,"[Ne] 3s2 3p5");
strcpy(E[ 24].name,"Chromium");
strcpy(E[ 24].sym,"Cr");
E[24].at_no= 24;
E[24].at_wt= 52.00;
strcpy(E[ 24].crs,"bcc");
E[24].at_r= 125;
E[24].ion= 6.766;
E[24].en= 1.6;
E[24].density=7200;
E[24].mp= 2160;
E[24].bp= 2755;
strcpy(E[ 24].earr,"[Ar] 3d5 4s1");
strcpy(E[ 27].name,"Cobalt");
strcpy(E[ 27].sym,"Co");
E[27].at_no=27;
E[27].at_wt= 58.93;
strcpy(E[ 27].crs,"hcp");
E[27].at_r=125;
E[27].ion=7.86;
E[27].en= 1.8;
E[27].density=8900;
E[27].mp= 1765;
E[27].bp= 3170;
strcpy(E[27].earr,"[Ar] 3d7 4s2");
strcpy(E[ 29].name,"Copper");
strcpy(E[ 29].sym,"Cu");
E[29].at_no=29;
E[29].at_wt=63.55;
strcpy(E[ 29].crs,"fcc");
E[29].at_r=128;
E[29].ion=7.726;
E[29].en=1.9;
E[29].density=8930;
E[29].mp= 1356;
E[29].bp= 2868;
strcpy(E[ 29].earr,"[Ar] 3d10 4s1");
strcpy(E[ 66].name,"Dysprosium");
strcpy(E[ 66].sym,"Dy");
E[66].at_no= 66;
E[66].at_wt= 162.50;
strcpy(E[ 66].crs,"rhombic");
E[66].at_r= 175;
E[66].ion= 5.93;
E[66].en= 1.2;
E[66].density=8500;
E[66].mp= 1680;
E[66].bp= 2900;
strcpy(E[ 66].earr,"[Xe] 4f10 6s2");
strcpy(E[ 68].name,"Erbium");
strcpy(E[ 68].sym,"Er");
E[68].at_no= 68;
E[68].at_wt= 167.26;
strcpy(E[ 68].crs,"hcp");
E[68].at_r=173;
E[68].ion=6.10;
E[68].en= 1.2;
E[68].density=9000;
E[68].mp= 1770;
E[68].bp= 3200;
strcpy(E[ 68].earr,"[Xe] 4f12 6s2");
strcpy(E[ 63].name,"Europium");
strcpy(E[ 63].sym,"Eu");
E[63].at_no= 63;
E[63].at_wt= 151.96;
strcpy(E[ 63].crs,"bcc");
E[63].at_r= 198;
E[63].ion= 5.67;
E[63].en= 1.1;
E[63].density=5200;
E[63].mp= 1100;
E[63].bp= 1712;
strcpy(E[ 63].earr,"[Xe] 4f7 6s2");
strcpy(E[ 9].name,"Fluorine");
strcpy(E[ 9].sym,"F");
E[9].at_no=9;
E[9].at_wt=19.00;
strcpy(E[ 9].crs,"cubic");
E[9].at_r=60;
E[9].ion=17.422;
E[9].en=4.0;
E[9].density=1.7;
E[9].mp=53.5;
E[9].bp=85.01;
strcpy(E[ 9].earr,"[He] 2s2 2p5");
strcpy(E[ 87].name,"Francium");
strcpy(E[ 87].sym,"Fr");
E[87].at_no=87;
E[87].at_wt=223;
strcpy(E[ 87].crs,"bcc");
E[87].at_r= 270;
E[87].ion= 4.0;
E[87].en= 0.7;
E[87].density=1870;
E[87].mp=303;
E[87].bp= 920;
strcpy(E[87].earr,"[Rn] 7s1");
strcpy(E[ 64].name,"Gadolinium");
strcpy(E[ 64].sym,"Gd");
E[64].at_no= 64;
E[64].at_wt= 157.25;
strcpy(E[ 64].crs,"hcp");
E[64].at_r= 178;
E[64].ion=6.14;
E[64].en= 1.2;
E[64].density=7900;
E[64].mp= 1585;
E[64].bp= 3000;
strcpy(E[ 64].earr,"[Xe] 4f7 5d1 6s2");
strcpy(E[ 31].name,"Gallium");
strcpy(E[ 31].sym,"Ga");
E[31].at_no=31;
E[31].at_wt=69.72;
strcpy(E[ 31].crs,"fcc");
E[31].at_r= 121;
E[31].ion= 5.999;
E[31].en= 1.6;
E[31].density=5950;
E[31].mp=302.9;
E[31].bp= 2676;
strcpy(E[ 31].earr,"[Ar] 3d10 4s2 4p1");
strcpy(E[ 32].name,"Germanium");
strcpy(E[ 32].sym,"Ge");
E[32].at_no=32;
E[32].at_wt=72.59;
strcpy(E[ 32].crs,"cubic");
E[32].at_r=122;
E[32].ion=7.899;
E[32].en= 1.8;
E[32].density=5400;
E[32].mp= 1210.5;
E[32].bp= 3100;
strcpy(E[32].earr,"[Ar] 3d10 4s2 4p2");
strcpy(E[ 79].name,"Gold");
strcpy(E[ 79].sym,"Au");
E[79].at_no=79;
E[79].at_wt= 196.97;
strcpy(E[ 79].crs,"fcc");
E[79].at_r= 144;
E[79].ion= 9.225;
E[79].en= 2.4;
E[79].density=19300;
E[79].mp= 1336.1;
E[79].bp= 3239;
strcpy(E[79].earr,"[Xe] 4f14 5d10 6s1");
strcpy(E[ 72].name,"Hafnium");
strcpy(E[ 72].sym,"Hf");
E[72].at_no= 72;
E[72].at_wt= 178.49;
strcpy(E[ 72].crs,"hcp");
E[72].at_r= 158;
E[72].ion= 7.0;
E[72].en= 1.3;
E[72].density=13300;
E[72].mp= 2423;
E[72].bp= 5700;
strcpy(E[ 72].earr,"[Xe] 4f14 5d2 6s2");
strcpy(E[ 67].name,"Holmium");
strcpy(E[ 67].sym,"Ho");
E[67].at_no=67;
E[67].at_wt=164.93;
strcpy(E[ 67].crs,"hcp");
E[67].at_r=176;
E[67].ion=6.02;
E[67].en=1.2;
E[67].density=8800;
E[67].mp=1734;
E[67].bp=2900;
strcpy(E[ 67].earr,"[Xe] 4f11 6s2");
strcpy(E[49].name,"Indium");
strcpy(E[ 49].sym,"In");
E[49].at_no=49;
E[49].at_wt=114.82;
strcpy(E[ 49].crs,"bc tetra");
E[49].at_r=162;
E[49].ion=5.786;
E[49].en=1.7;
E[49].density=7310;
E[49].mp=429.8;
E[49].bp=2300;
strcpy(E[ 49].earr,"[Kr] 4d10 5s2 5p1");
strcpy(E[ 53].name,"Iodine");
strcpy(E[ 53].sym,"I");
E[53].at_no=53;
E[53].at_wt=126.9;
strcpy(E[ 53].crs,"ortho");
E[53].at_r=135;
E[53].ion=10.451;
E[53].en=2.5;
E[53].density=4940;
E[53].mp=386.6;
E[53].bp=457.4;
strcpy(E[ 53].earr,"[Kr] 4d10 5s2 5p5");
strcpy(E[ 77].name,"Iridium");
strcpy(E[ 77].sym,"Ir");
E[77].at_no=77;
E[77].at_wt=192.2;
strcpy(E[ 77].crs,"fcc");
E[77].at_r=135;
E[77].ion=9.1;
E[77].en=2.2;
E[77].density=22420;
E[77].mp=2716;
E[77].bp=4800;
strcpy(E[ 77].earr,"[Xe] 4f14 5d7 6s2");
strcpy(E[ 26].name,"Iron");
strcpy(E[ 26].sym,"Fe");
E[26].at_no=26;
E[26].at_wt=55.85;
strcpy(E[ 26].crs,"bcc/fcc");
E[26].at_r=123;
E[26].ion=7.87;
E[26].en=1.8;
E[26].density=7870;
E[26].mp=1808;
E[26].bp=3300;
strcpy(E[ 26].earr,"[Ar] 3d6 4s2");
strcpy(E[ 36].name,"Krypton");
strcpy(E[ 36].sym,"Kr");
E[36].at_no=36;
E[36].at_wt=83.8;
strcpy(E[ 36].crs,"fcc");
E[36].at_r=201;
E[36].ion=13.999;
E[36].en=3.0;
E[36].density=3.49;
E[36].mp=116.5;
E[36].bp=120.8;
strcpy(E[36].earr,"[Ar] 3d10 4s2 4p6");
strcpy(E[ 57].name,"Lanthanum");
strcpy(E[ 57].sym,"La");
E[57].at_no=57;
E[57].at_wt=138.91;
strcpy(E[ 57].crs,"hcp/fcc/bcc");
E[57].at_r=187;
E[57].ion=5.577;
E[57].en=1.1;
E[57].density=6150;
E[57].mp=1190;
E[57].bp=3742;
strcpy(E[ 57].earr,"[Xe] 5d1 6s2");
strcpy(E[ 82].name,"Lead");
strcpy(E[ 82].sym,"Pb");
E[82].at_no=82;
E[82].at_wt=207.19;
strcpy(E[ 82].crs,"fcc");
E[82].at_r=174;
E[82].ion=7.416;
E[82].en=1.8;
E[82].density=11340;
E[82].mp=600.4;
E[82].bp=2017;
strcpy(E[ 82].earr,"[Xe] 4f14 5d10 6s2 6p2");
strcpy(E[ 71].name,"Lutetium");
strcpy(E[ 71].sym,"Lu");
E[71].at_no=71;
E[71].at_wt=174.97;
strcpy(E[ 71].crs,"hcp");
E[71].at_r=173;
E[71].ion=5.426;
E[71].en=1.2;
E[71].density=9800;
E[71].mp=1925;
E[71].bp=3600;
strcpy(E[ 71].earr,"[Xe] 4f14 5d1 6s2");
strcpy(E[ 12].name,"Magnesium");
strcpy(E[ 12].sym,"Mg");
E[12].at_no=12;
E[12].at_wt=24.31;
strcpy(E[ 12].crs,"hcp");
E[12].at_r=160;
E[12].ion=7.646;
E[12].en=1.2;
E[12].density=1741;
E[12].mp=924;
E[12].bp=1380;
strcpy(E[ 12].earr,"[Ne] 3s2");
strcpy(E[ 25].name,"Manganese");
strcpy(E[ 25].sym,"Mn");
E[25].at_no=25;
E[25].at_wt=54.94;
strcpy(E[ 25].crs,"cubic");
E[25].at_r=112;
E[25].ion=7.435;
E[25].en=1.5;
E[25].density=7440;
E[25].mp=1517;
E[25].bp=2370;
strcpy(E[ 25].earr,"[Ar] 3d5 4s2");
strcpy(E[ 80].name,"Mercury");
strcpy(E[ 80].sym,"Hg");
E[80].at_no=80;
E[80].at_wt=200.59;
strcpy(E[ 80].crs,"rhombic");
E[80].at_r=156;
E[80].ion=10.437;
E[80].en=1.9;
E[80].density=13590;
E[80].mp=234.3;
E[80].bp=629.7;
strcpy(E[ 80].earr,"[Xe] 4f14 5d10 6s2");
strcpy(E[ 42].name,"Molybdenum");
strcpy(E[ 42].sym,"Mo");
E[42].at_no=42;
E[42].at_wt=95.94;
strcpy(E[ 42].crs,"bcc");
E[42].at_r=136;
E[42].ion=7.099;
E[42].en=1.8;
E[42].density=10200;
E[42].mp=2880;
E[42].bp=5830;
strcpy(E[ 42].earr,"[Kr] 4d5 5s1");
strcpy(E[ 60].name,"Neodymium");
strcpy(E[ 60].sym,"Nd");
E[60].at_no=60;
E[60].at_wt=144.24;
strcpy(E[ 60].crs,"hcp/bcc");
E[60].at_r=181;
E[60].ion=5.49;
E[60].en=1.1;
E[60].density=6960;
E[60].mp=1297;
E[60].bp=3300;
strcpy(E[ 60].earr,"[Xe] 4f4 6s2");
strcpy(E[ 10].name,"Neon");
strcpy(E[ 10].sym,"Ne");
E[10].at_no=10;
E[10].at_wt=20.18;
strcpy(E[ 10].crs,"fcc");
E[10].at_r=160;
E[10].ion=21.564;
strcpy(E[ 10].eno,"NO DATA");
E[10].density=0.839;
E[10].mp=24.5;
E[10].bp=27.2;
strcpy(E[ 10].earr,"[He] 2s2 2p6");
strcpy(E[ 28].name,"Nickel");
strcpy(E[ 28].sym,"Ni");
E[28].at_no=28;
E[28].at_wt=58.71;
strcpy(E[ 28].crs,"fcc");
E[28].at_r=124;
E[28].ion=7.635;
E[28].en=1.8;
E[28].density=8900;
E[28].mp=1726;
E[28].bp=3005;
strcpy(E[ 28].earr,"[Ar] 3d8 4s2");
strcpy(E[ 41].name,"Niobium");
strcpy(E[ 41].sym,"Nb");
E[41].at_no=41;
E[41].at_wt=92.91;
strcpy(E[ 41].crs,"bcc");
E[41].at_r=143;
E[41].ion=6.88;
E[41].en=1.6;
E[41].density=8.570;
E[41].mp=2741;
E[41].bp=5200;
strcpy(E[ 41].earr,"[Kr] 4d4 5s1");
strcpy(E[ 7].name,"Nitrogen");
strcpy(E[ 7].sym,"N");
E[7].at_no=7;
E[7].at_wt=14.01;
strcpy(E[ 7].crs,"cubic");
E[7].at_r=71;
E[7].ion=14.534;
E[7].en=3.0;
E[7].density=1.165;
E[7].mp=63.3;
E[7].bp=77.3;
strcpy(E[ 7].earr,"[He] 2s2 2p3");
strcpy(E[76].name,"Osmium");
strcpy(E[ 76].sym,"Os");
E[76].at_no=76;
E[76].at_wt=190.2;
strcpy(E[ 76].crs,"hcp");
E[76].at_r=135;
E[76].ion=8.7;
E[76].en=2.2;
E[76].density=22480;
E[76].mp=3300;
E[76].bp=4900;
strcpy(E[76].earr,"[Xe] 4f14 5d6 6s2");
strcpy(E[ 8].name,"Oxygen");
strcpy(E[ 8].sym,"O");
E[8].at_no=8;
E[8].at_wt=16.00;
strcpy(E[ 8].crs,"rhombic");
E[8].at_r=60;
E[8].ion=13.618;
E[8].en=3.5;
E[8].density=1.33;
E[8].mp=54.7;
E[8].bp=90.2;
strcpy(E[ 8].earr,"[He] 2s2 2p4");
strcpy(E[ 46].name,"Palladium");
strcpy(E[ 46].sym,"Pd");
E[46].at_no=46;
E[46].at_wt=106.4;
strcpy(E[ 46].crs,"fcc");
E[46].at_r=137;
E[46].ion=8.34;
E[46].en=2.2;
E[46].density=12000;

program to find inverse of a matrix

by nitinmbhanu at 09:17 AM, 05/11/2012

//TO FIND INVERSE OF A MATRIX
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<graphics.h>
#include<iomanip.h>
float A[3][3],B[3][3];
int i,j,k,l,m,n,e,f,g,h;
float det=0;
void main()
{
clrscr();
cout<<"Enter the 3x3 matrix :\n";//Enters the matrix
for(i=0;i<3;i++)
for(j=0;j<3;j++)
 cin>>A[i][j];


//To find cofactor and determinant
for(i=0,k=1,m=2,e=-1,g=2;i<3;i++,e++,g--,k-=g,m-=e)
{
 for(j=0,l=1,n=2,f=-1,h=2;j<3;j++,f++,h--,l-=h,n-=f)
 {
  B[i][j]=pow(-1,(i+j))*((A[k][l]*A[m][n])-(A[m][l]*A[k][n]));
  if(i==0)
  {
    det+=A[i][j]*B[i][j];
  }
 }
}

cout<<"The determinant of the matrix is "<<det;

cout<<"\nCofactor of the matrix is :\n";
for(i=0;i<3;i++)
{
cout<<"\n";
for(j=0;j<3;j++)
cout<<setw(7)<<setprecision(3)<<B[i][j]<<"\t";
}
//To find adjoint
for(i=0;i<3;i++)
for(j=0;j<3;j++)
 A[i][j]=B[j][i];

cout<<"\nAdjoint of the matrix is :\n";

for(i=0;i<3;i++)
{
cout<<"\n";
for(j=0;j<3;j++)
cout<<setw(7)<<setprecision(3)<<A[i][j]<<"\t";

}

//To find inverse
for(i=0;i<=2;i++)
{
for(j=0;j<3;j++)
 A[i][j]*=(1/det);
}
cout<<"\nInverse of the matrix is :\n";
for(i=0;i<3;i++)
{
cout<<"\n";
for(j=0;j<3;j++)
{
 cout<<setw(7)<<setprecision(3)<<A[i][j]<<"\t";
}
}
getch();
}

function double pointer argument

by noscimo at 08:22 AM, 05/11/2012

hello!

I have a function with the following definition:

void functionName(void** a);

When I want to call that function how am I supposed to send the arguments?

Explanation regarding fstream ::ate

by maharjun at 06:17 AM, 05/11/2012

I have noticed the foolowing details regarding fstream.

the following combination of openstate flags do not truncate the files.

ios_base::out | ios_base::in | <any flag other than ios_base::trunc>
ios_base::out | ios_base::app | <any flag other than ios_base::trunc>

the following combinations are resulting in a failbit

ios_base::app
ios_base::ate
ios_base::app | aos_base::ate

and all other combinations open the file but truncate it.
is this standard behaviour? the reason i ask this is that i find it very wierd that the following combination truncates the file

ios_base::ate | ios_base::out

if this is standard behaviour, then there seems to be no way to use ate with out. i.e create an output stream which doesnt truncate without using app.

please confirm this. and suggest a workaround(if possible for the above problem).

VS 2010 and dll distribution

by Suzie999 at 05:32 AM, 05/11/2012

Whenever I create some small tool in c++ dll for use with another language, a new user always has to download
the microsoft redistributable package and install it.

Is there anyway to add the resources needed from the redist, to my dll?

How even do you know what resources it needs to function?

Sorry if the questions are noob.

Derivative of Polynomial with unknown term count?

by lxXTaCoXxl at 13:01 PM, 05/10/2012

I'm trying to upgrade my class library to my current mathematical skill set and am having trouble with multi-term polynomials, especially those I where I don't know how many terms the user will be putting in. I know that the formula for the first derivative of a polynomial is ax^n = n * ax^n-1; and the second derivative is the derivative of the first derivative. So for example:

Find the derivative of 4x^2:
4x^2 = 2 * 4x^2 - 1 = 8x^2-1 = 8x

Find the second derivative of 4x^3:
4x^3 = 3 * 4x^3-1 = 12x^3-1 = 12x^2
12x^2 = 2 * 12x^2-1 = 24x^2-1 = 24x

Right now I just have an algorithm for the first derivative of a single term polynomial:

    // Pesudocode (C++ Syntax):
    int Base = 0;
    int Exponent = 0;
    string Variable = "";

    cout << "Please input a polynomial to the first degree in the form (4 y 9): ";
    cin >> Base >> Variable >> Exponent;

    Base = Exponent * Base;
    Exponent = Exponent > 1 ? Exponent - 1 : 0;
    Variable = Exponent == 1 ? Variable : Variable + "^";
    Variable = Exponent == 0 ? "" : Variable;
    string exString = (Exponent == 1 || Exponent == 0) ? "" : (const char*)Exponent;

    cout << "The first derivative of the polynomial you submited is: " << Base << Variable << exString << "\n";

Chose to not work on the second derivatives until I figure out the whole parameter problem. I'm sure I have to use arrays or lists to accomplish this, but I'm not sure how the algorithm would work for a polynomial with 3 or more terms:

3x^2 + 13x + 4

Also the derivative of a constant (basically any number without a variable and exponent of 2 or higher) is equal to 0 for those who don't know and the derivative of infinity is undefined.

How do I define directory listing filter function?

by IMJS at 08:55 AM, 05/10/2012

I continue to use the same C++ libraries for COTS software that we use in my company. Their help files aren't great and when I send queries directly to the company it can be weeks or possibly months before I get a response. This, I think, is a simple problem that I'm hoping anyone who is handy at c++ (ie not me) can have a stab at answering.

I want to get a list of files in a directory that have the file extension 'ext'. I'm pretty sure that I want to use their library function dir_list() with a filter that only include files that have if the last 4 characters as ".ext". However, from their comments, I can't work out how to define this filter function or use it in dir_list(). Can anyone give me some hints, please? Yes, I can work around this, but it would be nice to use what is in the toolbox.

// Function to act as a filter to a directory list.
// This function must return True if a member of the list
// has past the criterion, and False if a member is to
// be excluded from the list due to failure to pass the
// filter criteria.
typedef bool (*filter_func)(const char[], const char[]);

void dir_list(
   StringList &file_list,   // List of files (returned)
   const char dir[],        // Directory to scan
   filter_func filter = NULL    // Filter function
);

fraction class istream errors

by FraidaL at 07:44 AM, 05/10/2012

The code is really long so I don't want to post all of it, but I'm posting the part I'm having an issue with. This is part of a fraction class I'm writing. Most of it is working but for there is something wrong with the istream because when I enter a fraction it just says d=0.
This is my input overload:

istream& operator>>(istream& in, fraction& x)
{
    int a;
    int b;
    char c;
    in >> a >> c >> b;
    fraction z=(a/b);
    x=z;
    return in;
}

This is the part in main:

fraction d;
    cout << "Enter a fraction: ";
    cin >> d;

    cout << "d=" << d << endl;

What am I doing wrong?

c++ 7 card poker evaluation

by henri18 at 07:43 AM, 05/10/2012

So; I have to determine if there is a) 3 of a kind b)4 of a kind c)straight. 
I have put the 7 cards into a 1 dimensional array and sorted them but I also need a case for not being more than 4 cards. I don't need to include suits. 
Here is what I have done:

include<iostream>
using namespace std;

include<cmath>
include<ctime>
include<cstdlib>
include<iomanip>
int main() 
{ 
const int size=7; 
int cards[size]={}; 
const int b=13; 
int tem[b]={0}; 
int a; int p; 
srand(time(0)); 
for(int i=0; i<10; i++)

{ for (int s=0; s<size; s++)
{ cards[s]=1+rand()%13; }
int i = 0, temp;
while( i < size ){ 
if ( i == 0 || cards[i - 1] <= cards[i] ) 
i++; 
else{ 
temp =cards[i]; 
cards[i] = cards[i - 1]; 
cards[--i] = temp;}}

for (p=0; p<b; p++) 
{tem[p-1]++; 
if(tem[p]==3) 
for (int m=0; m<size; m++) 
cout<<setw(4)<<cards[p]; cout<<"Three of a kind. "; 
cout<<endl;} } 
system("pause"); 
return 0; 
}

it does not work though 
4 of a kind is about the same as 3 of a kind 
no idea for the straight

C++ Form textbox string into SQL Database

by yongj at 03:21 AM, 05/10/2012

So let me start by saying that I am a complete beginner when coding in C++ windows/forms program. I was able to get my SQL database connection up with my program. I've ran some simple tests and it looks like my program is able to do simple queries such as inserting values into a table and such. My real hope, now, is for me to have my program take what's in one of my textboxes (username textbox for this example) and put it into my SQL database (Polynomigra), table (logins), field (username). I have not a clue how the syntax goes for this query. I also have no idea why the data type "string" is not existent in C++ windows forms applications. Can someone help me out? And again, I mention to you all that I am a complete beginner at this--I'm teaching myself how to do this.

Thanks and here's the code.

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                MySqlConnection^ con = gcnew MySqlConnection("Network Address=localhost;" "User Name='root';" "Password='password';" "database=Polynomigra");

                con->Open();

                string username = usernameText.Text;

                MySqlCommand^ cmdExecute = gcnew MySqlCommand("INSERT INTO logins VALUES ('1','testuser','testpassword')", con);
                MySqlDataReader^ reader = cmdExecute->ExecuteReader();

                con->Close();
             }

struct empty value

by noscimo at 01:21 AM, 05/10/2012

Hello !

I'm writing a program in C++ and I use a struct definition named Contact.
In a function in my program that returns an item of type Contact,i face the problem below:

Contact getContact(){

    Contact c;
    //do things
    if(condition)
        //assign c
     else
        //c is not assigned
     return c;
}

So when it goes in else statement,the c remains unassigned,and the return c gives an error of course.
Is there a way to assign it with something like null so the return statement wouldn't face a problem?
Contact is just a simple struct.

Colors in C++

by rony.united7 at 19:31 PM, 05/09/2012

How will I implement colors in a console application developed using C++? What are the color codes of different colors?

Eclipse C++ IDE

by rony.united7 at 19:22 PM, 05/09/2012

Can anyone help me with how to work on Eclipse C++ IDE? I need a clear set of instructions on how to connect server and database as well as how to compile and run standalone codes?

Classes And Overloading (.Net/Managed)

by triumphost at 15:58 PM, 05/09/2012

I'm trying to convert My Console classes to .Net classes because I can't use std::vector or anything like that in WindowsFormsApplications. So I decided to convert all Vectors to Lists and I thought that the classes work the same but my code below throws a massive amount of errors and I have no clue why.. It's quite short and simple to read.

using namespace System;
using namespace System::Collections::Generic;

template <typename T>
public ref class CustomType
{
    private:
        List<T> TypeData;

    public:
        CustomType() {}
        CustomType(...array<T^> ^Types)          //Basically Variadic Templates.. As good as it gets for MS2010..
        {
            for each (T^ o in Types)
                TypeData.Add(o);
        }
        ~CustomType() {}

        int size() {return TypeData.size();}

        CustomType& operator [](int I)
        {
            assert(I >= 0 && !TypeData.empty());
            return TypeData[I];
        }

        const CustomType& operator [](int I) const
        {
            assert(I >= 0 && !TypeData.empty());
            return TypeData[I];
        }

        operator const List<T>& () const
        {
            return TypeData;
        }

        bool operator == (const CustomType &CT) const
        {
            return (TypeData == CT.TypeData);
        }
};

I use the above like this:

    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
                 CustomType<int> Meh(0, 1, 2, 3, 4);
             }

But that does not work at all.. It's basically supposed to add Meh to the list within the class and I can access it at anytime to get the data.

Please help me. How do I overload in .Net and what is that Shevron? The ^ operator? I read that it's top level but have no clue what I read because I understood very little. Does ^ Replace the & operator?

USB Reset

by dark_sider_1 at 14:08 PM, 05/09/2012

Hi there,

I've been looking to figure out what a USB port does when it's overloaded by too much bandwidth (?), and it the port just shuts down, right? Might you have any ideas on where to look/what to look for with USB research? Is it even possible to automatically have a USB driver reset itself? Sorry if these are vague questions.

Thanks!!

Card Game problem

by zhengcyy at 12:34 PM, 05/09/2012

I'm creating the a Card game c++ program and I got some problem. PLZ help!!
I got few files:
Main.cpp (ask user which card game he want to play)
Card.h (creat rank and suit for cards)
War.h, War.cpp (creats War game)
TicTacToe.h, TicTacToe.cpp (creats TicTacToe game)
Game.h, Game.cpp (required to have a virtual function play() that all of the games inherit. Requires to use polymorphism to allow a single variable of type *Game() to access and play any of your games.

Here is my Main.cpp:

int main()
{
    int response =0;
    Game *myGame;

    while(response !=3)
    {
        cout<<"Press 1 to play War\n";
        cout<<"press 2 to play TicTacToe\n";
        cout<<"press 3 to quit\n";
        cin>>response;

        switch(response)
        {
            case 1:myGame = new War();
            break;
            case 2:myGame = new TicTacToe();
            break;
            default:return 0;
        }
        myGame->play();
    }
    delete myGame;
}

First question: Since I use 'new' operator to create War or TicTacToe. When I build it, it said 'can not convert TicTacToe* to Game* in assignment. What's wrong with that?

Here is my virtual function play() in Game.h:(nothing in there, Idk if I'm wrong)

virtual void play(){};

and I have no idea the construction of each War and TicTacToe should look like.
So here is my code:

Card.h

class Card
{
private:
    int rank;       //the number on the card
                    //jack=11; queen=12; king=13; ace=14
    CardSuit suit;  //the suit of the card

public:
    Card(int r, CardSuit s);//constructor
    int getRank() const;   //returns the card's rank
    void setRank(int);
    void setSuit(int);
    void display();         //displays the card to cout
                            //e.g.  if rank=11 and suit=HEARTS
                            //display  Jh

};

Card::Card(int r, CardSuit s)
{
    rank=r;
    suit=s;
}

War.h and constructor:

class War: public Game
{
    public:
        War();
        ~War();
        void play();
    private:
        Card *hc;
        Card *cc;


};

War::War() //constructor
{
    hc = new Card(2,HEARTS);
    cc = new Card(2,HEARTS);
}

Here is TicTacToe.h (it dosen't need to use Card class):

class TicTacToe
{
    public:
        TicTacToe();
        virtual ~TicTacToe();
        void printInstructions();
        void initializeBoard(char*);
        void displayBoard(char*);
        char winner(char*);
        bool isLegal(char*, int);
        void humanMove(char*);
        void computerMove(char *);
        void announceWinner(char winner);
        void play();
    protected:
    private:
    //The Tic-Tac-Toe board - a 9 character array
    //Each character can be an X, O, or a space
    //The space represents an open space on the board
    char * pb;
    char response; //User's response
    char turn; //keeps track of who's turn it is
};

TicTacToe::TicTacToe()  //constructor
{
    pb = new char[9];
}

Thanks for helping me debug! I really appreciate it!

EOF problem

by Suzie999 at 11:36 AM, 05/09/2012

I am downloading content from a web source using URLDownloadToFile winapi function
All is well, with that, the content is downloaded to the correct path.

My probems start when I try to read it, like below, the loop never exits.

myReadFile.open(sFile);

if (myReadFile.is_open()) 
        {
           while (!myReadFile.eof()) 
               {
                   //code;
               }
        }      
cout << "done" << endl; // is never displayed

It has been working before, the only thing which has changed is the content of the web source
and perhaps it's encoding.

Appreciate any advice on this matter.

Shift elements in an array using recursive function

by runstreet at 09:29 AM, 05/09/2012

Hi, everyone.
Hope you can help me to answer the question,
i am not familiar with recursive function...and i hope someone could help me..

Shift elements means
e.g.

array[ ] = {1, 2, 3, 4, 5, 6};
if the user input a value, say 2,
the array will become {5, 6, 1, 2, 3, 4},
the elements shift to the right by 2;

You may see the file attached as reference.

array1

Thanks.

Need solution to this?

by SanRubik at 08:56 AM, 05/09/2012

Our hardworking chef is bored of sleeping in his restaurants. He has decided to settle down. The first thing he must do is to find a suitable location to build a palatial home.

Think of the city as a two-dimensional grid. There are N restaurants in the city. Each of the chef's restaurant is a point denoted by (X , Y). A house can be located at a grid point (R, S) if the sum of the distances between this point and each of the restaurants is as small as possible. Find the number of possible house locations in the city to help out chef build a home.

More than one restaurant can be located at the same point.
Houses and restaurants can be located at the same point.
Every house must have integer co-ordinates. In other words, R and S are integers.
The distance between two points (A,B) and (C,D) is |A-C| + |B-D|. Here |X| is the absolute function.
Input

First line in the input contains T, number of test cases.
First line of each test case contains N, number of restaurants.
Each of the next N lines contain two integers X and Y separated by a space.

T <= 100
N <= 10^3
-10^8 <= X <=10^8
-10^8 <= Y <=10^8
Output

The number of possible locations (grid points) where houses can be built.
Example

Input:
3
5
0 0
-1 0
1 0
0 1
0 -1
5
31 11
30 -41
20 14
25 18
25 38
2
0 0
1 1

Output:
1
1
4

How to integrate QImage with boost::gil?

by stereomatching at 08:03 AM, 05/09/2012

#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP

#include <memory>

#include <boost/gil/gil_all.hpp>

#include <QtGui/QApplication>
#include <QtGui/QHBoxLayout>
#include <QtGui/QImage>
#include <QtGui/QLabel>
#include <QtGui/QWidget>

//#include "image_details.hpp"

static void x_gradient(boost::gil::gray8c_view_t const &src, boost::gil::gray8s_view_t const &dst)
{
    for (int y = 0; y != src.height(); ++y)
        for (int x = 1; x != src.width() - 1; ++x)
            dst(x, y) = (src(x - 1, y) - src(x + 1, y)) / 2;
}

inline void ComputeXGradientGray8(unsigned char const *src_pixels, ptrdiff_t src_row_bytes,
                                  int w, int h, unsigned char *dst_pixels, ptrdiff_t dst_row_bytes)
{
    using namespace boost::gil;
    gray8c_view_t src = interleaved_view(w, h, (const gray8_pixel_t*)src_pixels, src_row_bytes);
    gray8s_view_t dst = interleaved_view(w, h, (     gray8s_pixel_t*)dst_pixels, dst_row_bytes);

    x_gradient(src, dst);
}

static inline void x_gradient_qt(QImage const &src, QImage &dst)
{
    ComputeXGradientGray8(src.bits(), src.bytesPerLine(), src.height(),
                          src.width(), dst.bits(), dst.bytesPerLine());
}        

static void read_image()
{    
    QImage src("../GIL_with_Qt/images_00/coneL.bmp");
    QImage dst(src.width(), src.height(), src.format());

    x_gradient_qt(src, dst); //this will cause segmentation fault                      
}

#endif // EXAMPLE_HPP

depth : 8bit
format : QImage::Format_Indexed8
image width : 450
image height : 375
bytes per scan line : 452

How to integrate QImage with the example provided by the boost::gil?
This would cause segmentation fault yet I don't know why.
The algorithm seems nothing wrong
Thanks for your help

2008 scandalz.net
You or I must yield up his life to Ahrimanes. I would rather it were you. I should have no hesitation in sacrificing my own life to spare yours, but we take stock next week, and it would not be fair on the company. -- J. Wellington Wells
CountryUS
IP Address38.107.179.236
User AgentCCBot/1.0 (+http://www.commoncrawl.org/bot.html)