So i am trying to make a sorting algorithms visualizer with SFML. It is all good until i ask user input for the size of the array and which algorithm user wants to see it visualized. When i ask for user input, program executes in the background for a bit, sorting starts but i cant display it for couple of seconds.
int main(){
int Size = takeSize();
int choice = takeAlgorithm();
fillArray(Size);
while(window.isOpen()){
Event event;
while (window.pollEvent(event))
if(event.type == Event::Closed) window.close();
if(!sorted){
dispSort(0);
algorithmSelector(choice);
}
}
return 0;
}
Here is my main program. Everything works perfectly if i set the size of the array and which sorting algorithm will run before, but if i take input from user with takeSize() and takeAlgorithm() functions:
int takeSize(){
cout << "Please enter a number between 10 and 150 for the number of elements in the array: \n";
int vectorSize;
while(true){
cin >> vectorSize;
if(vectorSize >=10 && vectorSize <=199)
return vectorSize;
else{
cout << "Please enter a valid number between the given ranges!\n";
continue;
}
}
}
int takeAlgorithm(){
cout << "Please enter the corresponding number to select the sorting algorithm you want to see visualized: \n";
cout << "1-) Bubble Sort\n";
cout << "2-) Merge Sort\n";
cout << "3-) Insertion Sort\n";
cout << "4-) Selection Sort\n";
cout << "5-) Gnome Sort\n";
int number;
cin >> number;
return number;
}
Window displays late while sorting starts in the background.
Note: i use this in global scope -> RenderWindow window(VideoMode(601, 600), "Sorting Algorithm Visualizer!");
So an empty window shows up, then i enter the inputs after that window goes to the background.
The problem is that an SFML window doesn't display unless you poll for events so it won't show just because you constructed sf::RenderWindow
. Your code takes a while to reach the point when you poll for events because std::cin
blocks SFML.
Your options are to not use std::cin
and instead get keyboard input using SFML in a GUI or you can accept that the window won't open before an array size is entered. I think the latter actually makes more sense because it's not clear what your window would display if there isn't an array of elements to sort.