#include <iostream>using namespace std;int main(){int number;cout << "Press enter to exit";while(cin.get() != '\n'){// Process according to your input cout << number << endl;}cin.get();cin.get();return 0;}
Dev C++
Here use this:
just use
system("PAUSE");
it will stop execution, display "Press any key to continue..." and wait for you to press a key before closing. only one line, very simple.
system("PAUSE");
it will stop execution, display "Press any key to continue..." and wait for you to press a key before closing. only one line, very simple.
hey there I got an example program for directx game programming and I tried to compile it with dev-c++ and borland and even another weird one I don't remember and it displays an error message, dev-c++ says
[linker error]undefined reference to "DirectDrawCreate@12"
I don't know what to do I'm a beginner, here's the code(sorry the comments are in Spanish)
[linker error]undefined reference to "DirectDrawCreate@12"
I don't know what to do I'm a beginner, here's the code(sorry the comments are in Spanish)
/*========================================================================== * * PROGRAMA DE EJEMPLO NUMERO 3 * * PINTA UNA SERIE DE PUNTOS EN LA PANTALLA * DE DIFERENTE COLOR Y EN POSICION ALEATORIA * TERMINA AL PULSARSE LA TECLA "ESC" * ***************************************************************************///Se definen algunos datos generales como el nombre del programa. #define NAME "EJEMPLO"#define TITLE "COMO HACER UN VIDEOJUEGO"#define WIN32_LEAN_AND_MEAN//Se incluyen los ficheros fuente que son necesarios.#include <windows.h>#include <windowsx.h>//Es necesario incluir las Direct-Draw.#include "c:\mssdk\include\ddraw.h"//Se incluyen otros ficheros fuente necesarios.#include <stdlib.h>#include <stdarg.h>#include "resource.h"//Este es el manejador de la ventana de la aplicacion.HWND hwnd;//Estas estructuras de datos son necesarias para inicializar//y utilizar Direct-Draw:LPDIRECTDRAW lpDD; // El objeto Direct-DrawLPDIRECTDRAWSURFACE lpDDSPrimary; // FrontSurface de Direct-DrawLPDIRECTDRAWSURFACE lpDDSBack; // BackSurface de Direct-DrawDDSURFACEDESC ddsd; // Contiene la descripcion de una surfaceBOOL bActive; // almacena si la aplicacion esta activa//Se incluyen las estructuras de datos y funciones que se//han creado para hacer juegos.#include "engine.cpp"//Esta variable contiene el estado del programa.long programstatus=1;//Variables de uso temporalWORD x,y,color;//Esta funcion es llamada al finalizar el programa y en ella//se destruyen objetos que habian sido creados tales como//las surfaces de Direct-Draw y el propio objeto Direct-Draw. static void finiObjects( void ){ if( lpDD != NULL ) { if( lpDDSPrimary != NULL ) { lpDDSPrimary->Release(); lpDDSPrimary = NULL; } lpDD->Release(); lpDD = NULL; }}//Esta funcion contendra la inicializacion de las rutinas que se vayan creando.void GameInit(){ //Crea una lista de 480 punteros que contendran el principio //de cada una de las lineas que forman la pantalla fisica. NewScreenWin(pantallafisica,640,480); //La pantalla en uso sera la pantalla fisica SetActiveScreen(pantallafisica);}//Programa principal en si mismo. El programa Posee varios estadosvoid game(void){ //El primer estado es de inicializacion. //Pasa al estado numero dos despues de realizar dicha inicializacion. if(programstatus==1) { programstatus=2; } else //El segundo estado reliza la impresion de un punto en pantalla. if(programstatus==2) { //Obtiene el puntero a la pantalla PrepareRealScreen(); //Se obtiene una coordenada X aleatoria, comprendida entre 0 y 639. x=rand()%640; //Se obtiene la coordenada Y, comprendida entre 0 y 479. y=rand()%480; //El color sera aleatorio, entre 0 y 65535. color=rand(); //Se pinta el pixel en la pantalla. PutPixel(x,y,color); //Actualiza la pantalla, copiando el BackSurface sobre el FrontSurface UpdateRealScreen(); }}//WindowProc. Se ejecuta continuamente, es el blucle de mensajes de Windows.long FAR PASCAL WindowProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ){ //Analiza los mensajes switch( message ) { //Si se activa la aplicacion, bACtiva pasa a ser verdadero. case WM_ACTIVATEAPP: bActive = TRUE; break; //En caso de crearse la aplicacion no hace nada en especial. case WM_CREATE: break; //En caso de variarse el curso tampoco realiza nada en especial. case WM_SETCURSOR: SetCursor(NULL); return TRUE; //En caso de pulsarse una tecla, se realiza lo siguiente case WM_KEYDOWN: switch( wParam ) { //Si la tecla pulsada es "ESC" manda un mensaje de cerrar la //aplicacion. case VK_ESCAPE: PostMessage(hWnd, WM_CLOSE, 0, 0); break; } break; //En caso de acabarse la aplicacion se destruyen los objetos que hay //creados para asi poder salir del programa. case WM_DESTROY: finiObjects(); PostQuitMessage( 0 ); break; }return DefWindowProc(hWnd, message, wParam, lParam);}//Esta funcion es la primera que se ejecuta.//En ella se crea Direct-Draw y se llama a la inicializacion//de otras rutinas.static BOOL doInit( HINSTANCE hInstance, int nCmdShow ){ //Estructuras de datos necesarias para crear la ventana. WNDCLASS wc; //Estructuras usadas por Direct-Draw. DDSCAPS ddscaps; HRESULT ddrval; //Buffer de caracteres. char buf[256]; //Define las caracteristicas de la ventana de la aplicacion //que se esta creando. wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon( hInstance, IDI_APPLICATION ); wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hbrBackground = NULL; wc.lpszMenuName = NAME; wc.lpszClassName = NAME; RegisterClass( &wc ); //Llamada a CreateWindowsEx, crea la ventana en si. hwnd = CreateWindowEx( WS_EX_TOPMOST, NAME, TITLE, WS_POPUP, 0, 0, GetSystemMetrics( SM_CXSCREEN ), GetSystemMetrics( SM_CYSCREEN ), NULL, NULL, hInstance, NULL ); //Si no se ha creado la ventana, retorna generando un error. if( !hwnd ) { return FALSE; } //Muestra la ventana y la actualiza. ShowWindow( hwnd, nCmdShow ); UpdateWindow( hwnd ); //Aqui se crea el objeto Direct-Draw ddrval=DirectDrawCreate( NULL, &lpDD, NULL ); //Se comprueba si se ha creado correctamente if( ddrval == DD_OK ) { //Activa el modo exclusivo. ddrval = lpDD->SetCooperativeLevel( hwnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN ); if(ddrval == DD_OK ) { //Activa la resolucion de 640*480 en 16 bits de color ddrval = lpDD->SetDisplayMode( 640, 480, 16 ); if( ddrval == DD_OK ) { //Crea el FrontSurface y un BackSurface. ddsd.dwSize = sizeof( ddsd ); ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_SYSTEMMEMORY | DDSCAPS_COMPLEX; //Se crea un solo BackSurface. La memoria que usa el BackSurface //no estara en la tarjeta grafica, sino en la propia Ram del PC. ddsd.dwBackBufferCount = 1; ddrval = lpDD->CreateSurface( &ddsd, &lpDDSPrimary, NULL ); if( ddrval == DD_OK ) { //Se obtiene el puntero del BackSurface ddscaps.dwCaps = DDSCAPS_BACKBUFFER; ddrval = lpDDSPrimary->GetAttachedSurface(&ddscaps, &lpDDSBack); if( ddrval == DD_OK ) { //En caso de que todo haya salido bien //se inicializan otras rutinas y se //retorna TRUE. GameInit(); return TRUE; } } } } } //En caso de que alguna de las inicializaciones haya fallado //se devuelve un error y se retorna FALSE. wsprintf(buf, "Fallo al inicializar Direct-Draw (%08lx)\n", ddrval ); MessageBox( hwnd, buf, "ERROR", MB_OK ); finiObjects(); DestroyWindow( hwnd ); return FALSE;}//Llamada al bucle de mensajes. Desde aqui se llama al WindowProc.int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){ MSG msg; lpCmdLine = lpCmdLine; hPrevInstance = hPrevInstance; //En caso de que fallara la inicializacion, se retorna FALSE. if( !doInit( hInstance, nCmdShow ) ) { return FALSE; } //Se ejecuta siempre. while( 1 ) { //Si hay algun mensaje, se llama a WindowProc para //que gestione dicho mensaje. if( PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE )) { if( !GetMessage( &msg, NULL, 0, 0 ) ) return msg.wParam; TranslateMessage(&msg); DispatchMessage(&msg); } else //Si la aplicacion esta activa, se llama al nucleo del //programa en si. if( bActive ) { game(); } //En otro caso, espera la llegada de mensajes. else { WaitMessage(); } }}
This probably means you haven't linked the Direct-X libraries to your project. If you haven't got these, download them by using the WebUpdate module (Tools -> Check for updates/packages...).
When they´re all installed, you need to add the libraries to your project; go to Project -> Project Options, Parameters tab, and add in the field below 'Linker:', the following: "-lddraw" (without quotation marks, ofcourse). If you've done everything right, everything should be working.
I however strongly recommend using Allegro instead of DirectX, since it's much easier to learn and use, and it has plenty of functions to keep you coding for at least a decade.
The complete Allegro package (libs, headers, examples, docs and other stuff), can be downloaded by using the WebUpdate module.
When they´re all installed, you need to add the libraries to your project; go to Project -> Project Options, Parameters tab, and add in the field below 'Linker:', the following: "-lddraw" (without quotation marks, ofcourse). If you've done everything right, everything should be working.
I however strongly recommend using Allegro instead of DirectX, since it's much easier to learn and use, and it has plenty of functions to keep you coding for at least a decade.
The complete Allegro package (libs, headers, examples, docs and other stuff), can be downloaded by using the WebUpdate module.
You need to link to the appropriate directx library. I use OpenGL myself so I don't know exactly which one but press Alt+P and then go to the Parameters tab and click the add library or object button to select the library.
[edit:] Doh, that's what I get for opening lots of tabs. By the time I got to this one it'd been 2 mins ..
[edit:] Doh, that's what I get for opening lots of tabs. By the time I got to this one it'd been 2 mins ..
Quote:Original post by DIRECTXMEN
Here use this:
*** Source Snippet Removed ***
I have never got getch to work with Dev, what i use is first you need stdlib
#include <stdlib.h> it comes with dev and what someone else suggested
system("pause") it works best for me, or in the sams teach yourself C++ book there is a short command for you to write that tells the user to press enter to exit. And most tutorials I've seen online are geared toward dev
getch() is a non-standard function and is not compatible with ANSI regulations, which is what Dev C++ is based on. Do not use it unless you are using VC++, or an environment that you know supports it.
fflush( stdin );
bad coding
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1052863818&id=1043284351
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement