4

This is my C++ file:

#include <iostream>
#include "window.h"
#include <SDL2/SDL.h>

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

   if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
     std::cout << "Something went wrong" << std::endl;
}
  else { 
   SDL_CreateWindow("Neptune's Limit", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 768, SDL_WINDOW_OPENGL);
   }

   return 0;
}

When I run it, it flashes up for a half a second and then immediately closes. I have looked at the other posts about this, but the answer to them was about SDL_EVENT. I do not have that anywhere in my program.

What could be wrong?

scopchanov
  • 7,966
  • 10
  • 40
  • 68
Jiffis28
  • 65
  • 1
  • 7
  • 6
    Your window closes because your program ends. If you don't want it to end you'll need to do something to stop that. Take a look at the SDL sample programs and tutorials. – Retired Ninja Sep 07 '18 at 01:59
  • I prevented the program from ending but got the same result. I declared char a; and used std::cin >> a; but the window did the same thing – Jiffis28 Sep 07 '18 at 21:05
  • 1
    Add an event loop, something like what's described in this question and answer: https://stackoverflow.com/questions/34424816/sdl-window-does-not-show/41044089#41044089 – Retired Ninja Sep 07 '18 at 22:24
  • I will try this tomorrow, thank you. Been a long day. – Jiffis28 Sep 08 '18 at 03:26
  • Thanks so much @RetiredNinja – Jiffis28 Sep 10 '18 at 21:27

1 Answers1

5

After create SDL window, use while loop for maintain SDL window. I learn basic SDL functions with this tutorial

SIMPLE EXAMPLE

#include <iostream>
#include <SDL2/SDL.h>

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

   if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
     std::cout << "Something went wrong" << std::endl;
   } else { 
     SDL_CreateWindow("Neptune's Limit", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 768, SDL_WINDOW_OPENGL);
     while( true ) {
       // SDL RUNNING
       // Poll Event Code Maybe here!
     }
   }

   return 0;
}

Maybe this code doesn't exit because there's no exit-SDL code.

For exit program, add SDL_Event:

SDL POLL EVENT EX)

SDL_Event e;
while(true) { // SDL loop
  while( SDL_PollEvent( &event ) != 0 ) {
    if( event.type == SDL_QUIT ) {
      // Ctrl + C in console !
    }
  } // end of handling event.
}

Hope this helps you.

CKE
  • 1,533
  • 19
  • 18
  • 29
Zem
  • 464
  • 3
  • 14
  • Welcome to SO. Thanks for your answer and the hint for a tutorial. In SO, it is common to post your code directly, so maybe you could add the `while` loop to the code given in the question? – CKE Sep 13 '18 at 08:55
  • 1
    thank you for your advice. I add simple code for tutorial!! – Zem Sep 14 '18 at 00:24