100+ errors from wingdi.h when building - c++

So I am making a game, an ASCII dungeon explorer and I had a plan to get the window size and scale the display the inventory beside the dungeon. I went on google to find a function that would return the window size so I can print the inv on the side... The parts that are commented out is the code that I found and so I tried to put it in my main.cpp just to try it out. I planned to use other functions that I found to get the max size of the window and to set the size. This code that I pasted into my code was giving me loads of errors when I went to run the game, somewhere around 180 errors from a header file called wingdi.h. I googled a bit more and found people changing some definitions in the project properties which I tried and it gave me about 130 errors from different headers included in . Someone said that one of the variables is already declared in windows.h and the person that asked that question should change it to something else so I changed csbi to my_csbi, both didn't work. Some people also said it was a problem with the code so I decided to just leave it for now, and go back to my old code and do something else for now (I was getting frustrated, lol). I commented it all out, hoping to come back to it later. When I tried to run my game with all of that code gone, it gave me the same errors. Do I have to reinstall Visual Studio 2015? Starting my code from scratch or changing some definitions?
#include <iostream>
#include <conio.h>
//#include <Windows.h>
#include "GameSystem.h"
using namespace std;
int main()
{
//int x = 0;
//int y = 0;
//CONSOLE_SCREEN_BUFFER_INFO my_csbi;
//GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &my_csbi);
//x = my_csbi.srWindow.Right -my_csbi.srWindow.Left + 1;
//y = my_csbi.srWindow.Bottom -my_csbi.srWindow.Top + 1;
//printf("columns: %d\n", x);
//printf("rows: %d\n", y);
GameSystem gameSystem("level1.txt");
gameSystem.playGame();
printf("Enter any key to exit...\n");
int tmp;
cin >> tmp;
return 0;
}
I am fairly new to programming so I'm sorry if my question is stupid or "simple" and if that offended you in some shape or form. :)
Thanks, Bulky.
EDIT: All the "solutions" others got didn't work for me and I decided to ask this because after I commented out all that code, my old code didn't even run (it was perfect before).

You never include <WinGdi.h> directly. You always include <Windows.h>, which pulls in the required headers implicitly.
The GDI functions (from <WinGdi.h>) aren't going to do you any good if you are writing a console application. The GetConsoleScreenBufferInfo function is probably what you want to be using, but it is not a GDI function. It is a kernel function. Again, although it is technically declared in <WinCon.h>, you are not supposed to include that header directly. Just include <Windows.h>.
The following code works fine for me
(other than the fact that std::cin doesn't actually work for "enter any key to exit..."):
#include <iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
int main()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
int x = csbi.srWindow.Right - csbi.srWindow.Left + 1;
int y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
printf("columns: %d\n", x);
printf("rows: %d\n", y);
printf("Enter any key to exit...\n");
int tmp;
cin >> tmp;
return 0;
}
Output:
columns: 90
rows: 33
Enter any key to exit...
If it does not work for you, one of the following must be true:
1. The problem resides in "GameSystem.h", which you have not shown us.
(It is fine—in the future, please post code as text, not pictures.)
2. You have created the wrong type of project (recreate a new project using the Win32 Console Application template).
3. There is something wrong with your installation of Visual Studio (try reinstalling).

Related

Update getmaxyx() return values (ncurse / C++)

So, I'm, trying to be able to correctly resize my console window using ncurse in C++. I've been able to catch when the window is resize, the problem is that I'm not 100% sure how should I proceed after that. Let's say I have this loop in my main function (after initializing ncurse and those things...):
while(ch = getch())
{
if(ch == KEY_RESIZE)
{
DoSometing();
}
}
As I said the DoSomething in that example is called. But if I try to use ncurse's functions to get the new size of the window with
getmaxyx(stdscr, yMax, xMax);
I'm get the same values (the initial values) over and over again. I guess that's because when I do initscr(), the window size is stored somewhere and that's the value that the getmaxyx function provides. I've tried to do something like call endwin() and the again initscr() to restore those values, but that doesn't seem to work, the value that getmaxyx returns is fixed.
After searching for alternative solutions, I kind of solve the problem, using some other libraries. That's an small example, which actually works as I wanted:
#include <cstdlib>
#include <ncurses.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
initscr();
noecho();
box(stdscr, 0, 0);
struct winsize w;
int ch, x, y;
while(ch = getch())
{
if(ch == KEY_RESIZE)
{
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
resize_term(w.ws_row, w.ws_col);
clear();
box(stdscr, 0, 0);
}
refresh();
}
}
The thing is I'm kind of worried about portability while using this new libraries (I'm not completely sure, because I haven't started testing yet, but I understand that ncurse programs can be port to Windows).
I would really appreciate any information about how to do this in ncurse without using any other library (if it's possible), if what I'm doing now is OK or if I should be doing it in any other way. Any hint in the right direction is what I'm looking for :)
I'm using Arch Linux (kind of noobie) and qtile as a window manager. If you need any other relevant information, just ask me. Thanks for the help!
This is causing the example to produce bogus results:
if(ch = KEY_RESIZE)
since it is always true (not a comparison, but an assignment). The "something" is not doing anything useful, because the condition is incorrect.
Change that to
if(ch == KEY_RESIZE)
and get rid of
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
resize_term(w.ws_row, w.ws_col);

Recursive code exits with exit code 3221225477

I am new to c++ programming and StackOverflow, but I have some experience with core Java. I wanted to participate in programming Olympiads and I choose c++ because c++ codes are generally faster than that of an equivalent Java code.
I was solving some problems involving recursion and DP at zonal level and I came across this question called Sequence game
But unfortunately my code doesn't seem to work. It exits with exit code 3221225477, but I can't make anything out of it. I remember Java did a much better job of pointing out my mistakes, but here in c++ I don't have a clue of what's happening. Here's the code btw,
#include <iostream>
#include <fstream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
int N, minimum, maximum;
set <unsigned int> result;
vector <unsigned int> integers;
bool status = true;
void score(unsigned int b, unsigned int step)
{
if(step < N)
{
unsigned int subtracted;
unsigned int added = b + integers[step];
bool add_gate = (added <= maximum);
bool subtract_gate = (b <= integers[step]);
if (subtract_gate)
subtracted = b - integers[step];
subtract_gate = subtract_gate && (subtracted >= minimum);
if(add_gate && subtract_gate)
{
result.insert(added);
result.insert(subtracted);
score(added, step++);
score(subtracted, step++);
}
else if(!(add_gate) && !(subtract_gate))
{
status = false;
return;
}
else if(add_gate)
{
result.insert(added);
score(added, step++);
}
else if(subtract_gate)
{
result.insert(subtracted);
score(subtracted, step++);
}
}
else return;
}
int main()
{
ios_base::sync_with_stdio(false);
ifstream input("input.txt"); // attach to input file
streambuf *cinbuf = cin.rdbuf(); // save old cin buffer
cin.rdbuf(input.rdbuf()); // redirect cin to input.txt
ofstream output("output.txt"); // attach to output file
streambuf *coutbuf = cout.rdbuf(); // save old cout buffer
cout.rdbuf(output.rdbuf()); // redirect cout to output.txt
unsigned int b;
cin>>N>>b>>minimum>>maximum;
for(unsigned int i = 0; i < N; ++i)
cin>>integers[i];
score(b, 0);
set<unsigned int>::iterator iter = result.begin();
if(status)
cout<<*iter<<endl;
else
cout<<-1<<endl;
cin.rdbuf(cinbuf);
cout.rdbuf(coutbuf);
return 0;
}
(Note: I intentionally did not use typedef).
I compiled this code with mingw-w64 in a windows machine and here is the Output:
[Finished in 19.8s with exit code 3221225477] ...
Although I have an intel i5-8600, it took so much time to compile, much of the time was taken by the antivirus to scan my exe file, and even sometimes it keeps on compiling for long without any intervention from the anti-virus.
(Note: I did not use command line, instead I used used sublime text to compile it).
I even tried tdm-gcc, and again some other peculiar exit code came up. I even tried to run it on a Ubuntu machine, but unfortunately it couldn't find the output file. When I ran it on a Codechef Online IDE, even though it did not run properly, but the error message was less scarier than that of mingw's.
It said that there was a run-time error and "SIGSEGV" was displayed as an error code. Codechef states that
A SIGSEGV is an error(signal) caused by an invalid memory reference or
a segmentation fault. You are probably trying to access an array
element out of bounds or trying to use too much memory. Some of the
other causes of a segmentation fault are : Using uninitialized
pointers, dereference of NULL pointers, accessing memory that the
program doesn’t own.
It's been a few days that I am trying to solve this, and I am really frustrated by now. First when i started solving this problem I used c arrays, then changed to vectors and finally now to std::set, while hopping that it will solve the problem, but nothing worked. I tried a another dp problem, and again this was the case.
It would be great if someone help me figure out what's wrong in my code.
Thanks in advance.
3221225477 converted to hex is 0xC0000005, which stands for STATUS_ACCESS_VIOLATION, which means you tried to access (read, write or execute) invalid memory.
I remember Java did a much better job of pointing out my mistakes, but here in c++ I don't have a clue of what's happening.
When you run into your program crashing, you should run it under a debugger. Since you're running your code on Windows, I highly recommend Visual Studio 2017 Community Edition. If you ran your code under it, it would point exact line where the crash happens.
As for your crash itself, as PaulMcKenzie points out in the comment, you're indexing an empty vector, which makes std::cin write into out of bounds memory.
integers is a vector which is a dynamic contiguous array whose size is not known at compile time here. So when it is defined initially, it is empty. You need to insert into the vector. Change the following:
for(unsigned int i = 0; i < N; ++i)
cin>>integers[i];
to this:
int j;
for(unsigned int i = 0; i < N; ++i) {
cin>> j;
integers.push_back(j);
}
P.W's answer is correct, but an alternative to using push_back is to pre-allocate the vector after N is known. Then you can read from cin straight into the vector elements as before.
integers = vector<unsigned int>(N);
for (unsigned int i = 0; i < N; i++)
cin >> integers[i];
This method has the added advantage of only allocating memory for the vector once. The push_back method will reallocate if the underlying buffer fills up.

Autoclicker using C++ to click in differnent intervals using RNG * Milliseconds to determine the time between clicks

I've been testing it for hours now and I just can't get it to work.
I'm trying to get an Autoclicker to work, using C++.
Said Program should be able to click without moving the mouse, not specified in the Programm.
The mouse only needs to left-click.
This has to be done in different intervals. My idea was, that we use a Random Number Generator (RNG) to determine a Number between 1 and 100.
This step is easy just using a (rand() % 6) + 1 command.
Loading the library you can use the command srand(time(0)) before the for function to actually randomize it.
My problem lies after that.
How to I get the resulting random number to be multiplied by Milliseconds (preferably also randomized) and then use the resulting time as the time beween mouse outputs?
I know this is much to ask but I'm pretty new to coding and this is a passion project. If anyone would be experienced enough to help me out with my problem it would be greatly appreciated.
Edit: This is what I have so far, I know it's not much but it works. Improvements are obviously welcome though.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
/* function main begins program execution */
int main(void) {
int i;
srand(time(0));
for (i = 1; i < 2; i++) {
printf("%d ", 1 + (rand() % 6));
}
cin.get();
return 0;
}

Did I miss a code or something?

so I'm trying to write a guess the number game in C++.The computer is Supposed to take a random number with 4 digits then the player should enter a number too.Rules are:
if the computer chooses:1234
And the player enters:1356
1 must be displayed in green,3 must in yellow since it's in the wrong place and 5&6 in red.the game goes on till the player gets the right answer.
#include<iostream>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include<unistd.h>
using namespace std;
int main()
{
int b;
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
cout<<"System is now generating a number...."<<"\n";
int *Number = new int[4];
srand (time(NULL));
for(int counter=0;counter<4;)
{
Number[counter]=(rand()%9)+1;
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
{
counter ++;
}
else
{
counter--;
}
}
cout<<Number[0]<<Number[1]<<Number[2]<<Number[3]<<"\n";
int *Guess=new int[4];
cout<<"please enter 4 digits for your number"<<"\n";
for(int counterG=0;counterG<4;counterG++) //line 34
{
cin>>Guess[counterG];
for(int counter;counter<4&counter>0;)
{
if((counter=counterG)&(Guess[counterG]=Number[counter])) //line 40
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,10);
cout<<b<<"\n";
}
if((counter=counterG)&(Guess[counterG]==Number[counter- 1]|Guess[counterG]==Number[counter+1]|Guess[counterG]==Number[counter-2]|Guess[counterG]==Number[counter+2]))
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,14);
cout<<b<<"\n";
}
else
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,12);
cout<<b<<"\n";
}
}
}
now the program is fine until line 34 but nothing happens after that!
It just gets the player digits
I'd be glad if you could tell me what I've done wrong
Not a complete answer, but it's too long for a comment:
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
This line alone contains a lot of errors:
To have the logical AND operator you need &&, not &.
You have typed an extra 2] at the beginning of the second line. I hope it's just a typo that you introduced when writing the question.
The first time you run this, counter is 0. What happens when you try to access Number[counter-3]? It's an out of bounds access, which leads to Undefined Behaviour, which can lead to anything.
And there are probably many more.
What to do now:
Work on your code indentation. It's really bad.
Start from a much simpler program, and verify that it works. Then, add one small step, verify it, and don't move on until you are happy with the result
Turn on your compiler warnings. Warnings are your friends, not a boring annoyance
Learn how to use a debugger. You won't go very far without debugging.
1- replace & with &&(AND operator)
2- take input in a simple integer variable and then validate the number by performing first check of number greater than 0 and less than 9999.
3- then seperate digits from this variable and then assign those digits to aaray indexes respectvely.

Eclipse Method could not be resolved in a simple program C++

I have an issue with Eclipse Indigo complaining that methods of a class couldn't be resolved, but compiling anyway and working correctly (AFAIK). It's a very simple program. Here is Population.cpp:
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include "Population.h"
Population::Population() {
// TODO Auto-generated constructor stub
}
Population::~Population() {
// TODO Auto-generated destructor stub
}
void Population::initializePop(int numBits, int N) {
srand((unsigned)time(0));
for(int i=0; i<N; i++) {
x[i] = (char*) calloc(numBits, sizeof(char));
for(int j=0; j<numBits; j++) {
if( rand() < 0.5 )
x[i][j] = 0;
else
x[i][j] = 1;
}
}
}
char** Population::getX() {
return x;
}
void Population::printStuff() {
std::cout << "Whatever";
}
Now, I build that code and everything is fine. In another project within Eclipse, I'm calling this code like this:
#include <typeinfo>
#include <string.h>
#include <iostream>
#include "cute.h"
#include "ide_listener.h"
#include "cute_runner.h"
#include "Population.cpp"
void testPopulationGeneration() {
Population* p = new Population;
int N = 10;
int bits = 4;
char** pop;
ASSERTM("Population variable improperly initialized", dynamic_cast<Population*>(p));
std::cout << p->printStuff();
std::cout << "Ok...";
p->initializePop(bits, N);
pop = p->getX();
ASSERTM("Pop not correct size.", sizeof(pop) == 10);
}
As you can see I'm also running the CUTE plugin for TDD in C++. It doesn't complain when I declare p as type Population and the first assertion passes. I'm somewhat new to C++, but I did make sure to add the project that Population.cpp is from to the include path for the test project.
It's not a huge deal as it's not affecting anything obvious to me, but it's still very annoying. I don't see a situation where it should do this.
Thanks for any help!
Try this:
In your project explorer window, right click on your project -> Index -> Rebuild
This could be an indexing issue related to external #include headers not found. Follow the steps below and see if it helps:
Go to each of your custom #include (e.g. "cute.h") and press
F3 (i.e. "Show declaration"); see if it's able to access that file
or not; if not copy those files on some notepad
If the file is not accessible, then locate it paths in your
directory structure; e.g. "cute.h" and "a.h" are located at,
"C://Eclipse/MyWork/Workspace/Project/include_1" and
"ide_listener.h" is located
at,"C://Eclipse/MyWork/Workspace/Project/include_2", then copy both
the folder paths on some notepad
Inside Eclipse go to Project -> Properties -> C/C++ General ->
Paths and Sybmols; you will see several tabs as Includes,
Sybmols, Library Paths ...
Click Library Paths -> Add -> Workspace... -> <locate the above
folder paths> and press OK
Let the indexer rebuild; now again follow the step (1); hopefully
the files should be accessible
For future safety for larger files, go to Window -> Preferences ->
C/C++ -> Editor -> Scalability -> "Enable scalability mode when
..." and set the number of lines to some big number such as
500000 and press "OK";
The last step is needed, because when your file grows in line number and if exceeds the above number then eclipse will stop showing definitions for some "scalability" reasons, even though it would have indexed.
sizeof(pointer) returns the size of the pointer (4 on 32-bit systems and 8 on 64-bit), not the size of what it points to! Save the dimensions in the class, and add a function to return them.
Also, in initializePop shouldn't you allocate the actual X array?
X = calloc(N, sizeof(char *));
Or rather, you should use new for allocation since you are using C++:
X = new char* [N];
and later:
X[i] = new char [numbits];
Not that i'm any expert at all but i just had a similar problem using.empty for whatever reason it will work if you change char to string minor change but resolved the issue on my program