I'd suggest you read a tutorial on C++, etc.. After you get the basics down, you'll realize what I did wasn't pro or anything and it was in fact basic. Now your teacher may not have taught you for-loops yet and I'm sorry about that but I will teach you it now so that you understand it. You can of course convert it to a while loop if you like but I suggest you learn a for-loop because it is the most important loop you'll ever learn. Well at least it's the most used/useful.
Tutorial sites will usually teach you this around lesson 4-5 I believe.
Anyway..
A for-loop is like a while loop except that it increments the values you specify. The for-loop I used says:
Enter the number of values you will be entering. (This is the amount of grades the user wants to calculate the average from.)
While "SomeVariable" is less than the number they entered, keep looping. Increment "SomeVariable" at the end of the loop.
Thus these two are equivalent:
int Result = 0, NumberOfGrades = 0;
double Sum = 0;
cout<<"Enter the Number of Grades you wish to calculate the average with: "<<endl;
cin>> NumberOfGrades;
cin.ignore();
while(Result < NumberOfGrades)
{
double X = 0;
cout<<"Enter Grade # 1 (2,3,4,5, etc..): "<<endl; //I did "Enter Grade # "<<Result <<"endl;
cin>>X;
cin.ignore(); //Ignore the enter button/new-line character.
Sum = Sum + X; //This is the same as Sum += X;
++Result; //This is the same …
You are checing whether the mouse is moving or not? Thus you need to do something like (PSuedo code):
int X = 0, Y = 0;
int X2 = 0, Y2 = 0;
bool MouseDrag = false;
if (MOUSE_LEFTButton == DOWN)
{
GetMousePos(&X, &Y);
MouseDrag = true;
}
if ((MOUSE_LEFTButton == UP) && MouseDrag)
{
MouseDrag = false;
GetMousePos(&X2, &Y2);
}
It's just PSuedo code since I'm not familiar with GLUT. If you need a WinAPI solution, I can show you that and maybe you can do that in glut. But it should be done like the above.
Uh we don't do homework without you showing effort. In fact, we don't do homework at all but I'd definitely be gladd to help or show you how if you can show me that you tried something or understand pointers/arrays.
char is just like any other Data type. You can do:
char VariableB = 'B';
char K = 'K';
char Zero = '0';
char NULLS = '\0';
//A char is always 1 character in length. An array of chars is called a string:
char Str[] = {'T', 'R', 'I', 'U', 'M', 'P', 'H'};
//which is equivalent to:
string Str = "Triumph";
//You can change chars as well (Just like any other variable):
K = VariableB;
//You can also get user input into a char:
int main()
{
char VariableChar;
cout<<"Please enter the first Character of your first name: "<<endl;
cin>> VariableChar;
}
//It can also be used in a switch case statement and be casted to an int.
int main()
{
char A = 'A';
cout<<"The ASCII value of character A is: << (int) A <<endl;
char Choice = '0';
cout<<"Please choose a letter from A - C: "<<endl;
cin>> Choice;
cin.ignore();
switch(Choice)
{
case 'A': cout<<"You chose A";
break;
case 'B': cout<<"You chose "B";
break;
case 'C': cout<<"You chose "C";
break;
default: cout<<"You didn't enter a character between A and C;
break;
}
if (Choice == 'A')
{
cout<<"Choice was equivalent to character A.."endl;
cout<<"Choice has an ASCII value of: "<< (int) Choice <<endl;
}
}
Let me know which part you didn't understand? I'll break it down or change it. I only wrote that quickly and didn't give it much thinking.
The only problem I spotted after a very very quick look at your code was that you never incremented "Counter" in your Input function. Thus you were stuck in an infinite loop.
I haven't tested this but meh.. Since I see you already posted and shown an attempt, I'll show a suggestion. Now this code has no error handling and is definitely error prone. I'll leave that up to you to do. The idea is fairly simple. You get the user input and store how many values they entered. Sum them up on the spot. Return both of those. Finally, Calculate the average. Check the range of the average and return the letter that matches. Do some error checking of course!
#include <iostream>
#include <windows.h>
using namespace std;
int Input(double &Num) //Returns Number of Values entered. Num = Sum of values entered.
{
int Result = 0, Args = 0;
cout<<"Enter the Number Of Grades You'll be Entering: "<<endl;
cin>>Args;
cin.ignore();
for(Result = 0; Result < Args; ++Result)
{
int X = 0;
cout<<"\n\nPlease Enter Grade #"<<Result + 1<<": ";
cin>>X;
cin.ignore();
Num += X;
}
return Result;
}
double Calc(int Args, double Sum)
{
if (!Args)
return 0; //This is so we cannot divide by 0.
return ((Sum / Args) * 1.0);
}
char Grade(double Average)
{
if (!Average)
return '0';
int Rounded = static_cast<int>(Average);
if (Rounded >= 93)
return 'A';
else if (Rounded >= 85)
return 'B';
else if (Rounded >= 77)
return 'C';
else if (Rounded …
Ahh that's much much better now. I can tell you have shown effort so I'll show you what they meant.
Now the instructions say that it wants a boolean function that takes a "Date" argument.
By that, the teacher means:
bool sameMonth(Date date)
{
//..... Compare the Months..
}
In the below code I'm about to post, you'll see something like:
Constructor(Params) : Member(Param1), Member2(Param2) {}
//That's essentially the same as:
Constructor(Params)
{
Member(Param1);
Member2(Param2);
}
Now that I see you have 99% of it done, here's how I implemented it.. now there's a couple things different but it's exactly the same as yours:
#include <iostream>
#include <windows.h>
class Date
{
private:
std::string Month;
int Day;
int Year;
public:
Date();
Date(std::string month, int day, int year);
void setMonth(std::string month);
void setDay(int day);
void setYear(int year);
std::string getMonth();
int getDay();
int getYear();
void printDate();
bool sameMonth(const Date &date);
};
Date::Date() : Month("January"), Day(1), Year(2012) {}
Date::Date(std::string month, int day, int year) : Month(month), Day(day), Year(year) {}
void Date::setMonth(std::string month) {Month = month;}
void Date::setDay(int day) {Day = day;}
void Date::setYear(int year) {Year = year;}
std::string Date::getMonth() {return Month;}
int Date::getDay() {return Day;}
int Date::getYear() {return Year;}
void Date::printDate(){std::cout<<"\nThe Date is: "<<Month<<" "<<Day<<", "<<Year<<std::endl;}
bool Date::sameMonth(const Date &date) {return !_stricmp(date.Month.c_str(), Month.c_str());}
Something like the below should suffice:
int main()
{
Date Date1("September", 30, 2012);
Date Date2("September", 29, 2012);
std::cout<<Date1.sameMonth(Date2);
}
Similar to that. I had to go to the Java folder, copy the JNI.h, JNI_MD.h (Machine dependent) to my project and compile with a .def file.
After that, it stopped crashing =] Thanx for try though :D
:S What do you mean it can't do that? Data.resize(Foo.Size()); is already there?
I found the problem but I cannot solve it.. if I declare variables within that JNI function, it crashes.. If I don't, it works just fine. Is there a way around this? The following was my testing solution which I don't want at all.. Nevertheless, it works but for all the wrong reasons and that means I cannot assign to the pointer.
Also I tried what you said, it still crashes.
#include "Library.h"
void NothingFunction()
{
std::vector<unsigned char> TEMP;
int Width = 0, Height = 0, Size = 0;
DoBitmap(TEMP, Width, Height, Size);
Bitmap K(TEMP, Width, Height, 24);
K.Save("C:/users/brandon/desktop/Footest.bmp");
}
JNIEXPORT void JNICALL Java_library_Library_GetGLBuffer(JNIEnv *env, jclass cls, jobject buffer)
{
/* The following crashes it..
unsigned char* bb = (unsigned char*)env->GetDirectBufferAddress(buffer);
NothingFunction();
*/
//But if I switch the order of the calls.. it works (Also I cannot declare variables within here.. it will crash):
NothingFunction();
unsigned char* bb = (unsigned char*)env->GetDirectBufferAddress(buffer);
}
Any way around the above?
I had absolutely no clue where to post this but I figured since it crashes on the C++ side, I'd ask here.
I have the following code:
Java side (Loads My C++ DLL just fine.. Passes it a ByteBuffer so that I can write to that):
import java.io.IOException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.nio.ByteBuffer;
public class Library
{
static{System.loadLibrary("TestDLL");}
static native void GetGLBuffer(ByteBuffer Buffer);
public static void main(String[] args) {
int BitsPerPixel = 32, Width = 344, Height = 336;
int IntSize = ((Width * BitsPerPixel + 31) / 32) * Height;
int ByteSize = IntSize * 4;
ByteBuffer Buffer = ByteBuffer.allocateDirect(ByteSize);
GetGLBuffer(Buffer); //Give C++/DLL the byte buffer.
//Frame F = new Frame("Testing Buffer", Buffer.array());
}
}
On the C++ Side I have (Load a bitmap, get the array of pixels from it.. write that array to the Java ByteBuffer):
#include "Library.h"
EXTERN_C void __stdcall Dobitmap(std::vector<unsigned char>& Data, int &Width, int &Height, int &Size)
{
int Bpp = 24;
Bitmap Foo("C:/Users/Brandon/Desktop/Untitled.bmp");
std::vector<RGB> Pixels = Foo.Foo();
Data.clear();
Data.resize(Foo.Size());
unsigned char* BuffPos = &Data[0];
for (int I = 0; I < Foo.Height(); ++I)
{
for (int J = 0; J < Foo.Width(); ++J)
{
*(BuffPos++) = Pixels[(Foo.Height() - 1 - I) * Foo.Width() + J].RGBA.B;
*(BuffPos++) = Pixels[(Foo.Height() - 1 - I) * Foo.Width() + J].RGBA.G;
*(BuffPos++) = Pixels[(Foo.Height() - 1 - I) * Foo.Width() + J].RGBA.R;
if (Bpp > 24)
*(BuffPos++) = Pixels[(Foo.Height() - 1 - I) * Foo.Width() + J].RGBA.A;
} …
Well I found that difficult to read.. You should really really format the code properly before posting it. I know it only takes two clicks to format it A-style but meh. If you did so, more people would take the time to read it.
Also I'm not sure how you got that to compile because there is no cstring.h and no iostream.h
Remove the .h from both of those headers and it'll compile fine.
Also you have quite a lot of compilation errors. If you aren't using std::
infront of standard library functions, then you need to have using namespace std
somewhere at the beginning of your code.
Main cannot be void! It must return an int.
Also after std::cin>>info[i].id;
you should use std::cin.ignore();
or else it will skip the next line due to the enter/return button being pressed. It needs some error checking for that as well because if the user enters a string, your program will end immediately!
Switch the getlines to cin>> with a cin.ignore.
If an if-else statement has more than one command following it that belongs to its body, it must have brackets..
else
{
std::cout<<"Please Enter BuyerID:";
std::cin>>buyid;
}
//NOT
else
std::cout<<"........";
std::cin>>buyid; //This is not part of the else statement since it's not in the body.
Here's a semi fixed version (Needs error checking as mentioned above, but other than that, the below works):
#include <iostream>
#include <cstring>
#include <conio.h>
#include <windows.h>
//using namespace std; //You can use …
Uhh you're calling the constructor before getting user input. The question wants you to get user input first THEN use that input to construct the object.
Thus get the user input, pass those values to the constructor. Also you might have had faster answers if you also posted the .cpp file associated with that header as I had to write it myself. I won't post it yet though until I am absolutely sure that you've tried it yourself. I've posted the main example though but as said above, I will hold off on posting the class itself.
According to the instructions your teacher gave you, you need to do something like this (I post this only because you tried, but I'd advise you to read a bit more carefully the requirements):
#include <iostream>
#include "Date.hpp"
using namespace std;
int main()
{
string Month = string();
int Day = 0, Year = 0;
Date Date1;
cout<<"Testing Constructor to see if it works..\n"<<endl;
cout<<"Month: "<<Date1.getMonth()<<endl;
cout<<"Day: "<<Date1.getDay()<<endl;
cout<<"Year: "<<Date1.getYear()<<endl;
cout << "\n********************************************************\n" << endl;
cout<<"Enter The Month: ";
cin>>Month;
cin.ignore();
cout<<"\nEnter The Day: ";
cin>>Day;
cin.ignore();
cout<<"\nEnter The Year: ";
cin>>Year;
cin.ignore();
Date1.setMonth(Month);
Date1.setDay(Day);
Date1.setYear(Year);
Date1.printDate();
Month.clear(); Day = 0; Year = 0;
cout << "\n********************************************************\n" << endl;
cout<<"Enter The Month: ";
cin>>Month;
cin.ignore();
cout<<"\nEnter The Day: ";
cin>>Day;
cin.ignore();
cout<<"\nEnter The Year: ";
cin>>Year;
cin.ignore();
Date Date2(Month, Day, Year);
Date2.printDate();
cout << "\n********************************************************\n" << endl;
return 0;
}
Looks correct. It does indeed work.
Make a file on your desktop called Foo.txt. Put the value 10 in it.
Run your program and type exactly this:
C:/Users/Username/Desktop/Foo.txt
Replace Username with your username.. It'll print 10.
Also note that the method you're currently reading with will break as soon as it hits the first Space or Newline character.
There is nothing wrong with your Vector.. It's the for-loop logic.for(counter = 0; counter < sOList.size(); counter++)
when that for-loop ends, counter will have retained its value from the last iteration.
you need:
for(unsigned int counter = 0; counter < sOList.size(); counter++)
That way, counter starts at 0 all the time then iterates the vector appropriately.
Line 47 should be: 'b' not 'd'.. selection = 'b';
Also might I suggest that when a case statement contains multiple statements, you might want to start using brackets. Reason being is because if it contains pointers or handles, it'll fall through (well happened to me a lot.. Compiler complained). It's just practice incase. Not required all the time. Also I'd suggest having a 'default: ' case.
instead of:
case 'b':
...
...
break;
//You can do:
case 'b':
{
.......
}
break;
default:
break;
Stack unwinds. When you do a recursive call, it keeps pushing onto the stack. Then you have your return if it's less than 0. At that point, it basically breaks out and starts unwinding and printing every a value that was entered. Well at least that's the way I was taught recursive stuff. Hopefully that's right so that I don't mislead you.
Hmm that crashes on the very last row if there is a dot.
Example, in the puzzle on the first post: ###..G..L
When it encounters a dot, it will throw an error. Other than that, that works fine.
How can I figure out where words intersect in the following?
AAAA#BBBB
.#.##C##H
.#.##D##I
.#...E.#J
##.##F##K
###..G..L
'#' represents the black spots in a crossword where you cannot fill in.
'.' represents the spots with missing letters that need to be filled in.
I've read the puzzle into a
vector<string> Horizontal;
vector<string> Vertical;
I can merge it or read it into a 2D array of strings as well but I cannot figure out where words intersect :S
I've got a list of all possible words that can fit into the spots given the letters that are currently there but I need a way to figure out where words intersect and where they don't so I can start filling it in.
Any ideas??
You shouldn't have to call that function every time. I "THINK" you can just iterate it just like a normal 2Darray OR use a pointer to iterate it.
Try it and see how it works out. If it doesn't work then I guess you are restricted to using that function for getting the elements.
We cannot help if we do not know what your function looks like :S I don't see any for-loops. I cannot tell from just reading that what the problem is. Perhaps you are accessing an invalid section in memory when trying to read/store the array?
That could be the cause of the crash perhaps.
But again, from looking at the above, we cannot even tell what is happening other than an array of variable types is being passed as an argument and stored all it's data to another array via a pointer?
Use a try catch or a step-through/variable watch to see what's going on.
Question for you.. Are you sure the following is correct?
if( lRet != ERROR_SUCCESS )
{
if( lRet == ERROR_FILE_NOT_FOUND )
{
bRet = FALSE ;
break ;
}
else
{
bRet = FALSE ; //Are you sure? :S
break ;
}
}
The reason I'm asking is because it's never true throughout that entire block :S
If ....... False else... False.. Thus there is no reason for the if statement correct?
ALSO just wanted to say that KEY_ALL_ACCESS |KEY_WOW64_32KEY Could be the problem. Why?
After the application has accessed an alternate registry view using one of the flags, all subsequent operations (create, delete, or open) on child registry keys must explicitly use the same flag. Otherwise, there can be unexpected behavior.
You seem to specify such a flag for opening only.. Thus the rest of stuff is undefined behaviour since you didn't explicity supply the same flag.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa384129(v=vs.85).aspx
That explains your flags and undefined behaviour but on top of that, it states that you should enumerate twice before opening.
Hopefully this solves your problems. Then again I could be wrong and you may have to wait on someone else's reply but I tried since I saw you waiting 17 hrs for one reply :P
It's automatic as far as I can remember. It's been a while since I did inheritance/poly but when a derived class has a function with the same name as the base class, the derived class's member function is said to override the base class's. Well I think so at least. I cannot guarantee that I'm right.
Anyway something like:
class A
{
public:
A(){}
void Foo(int K) {}
};
class B : public A
{
B() {}
void Foo(int K) {} //This should override the one in the base class "A".
void CallBaseFoo()
{
A::Foo(10); //Calls the base class' Foo instead of this class' Foo.
}
};
EDIT!! Found something on google that "MIGHT" be what you're looking for: http://oscience.info/computing-technology/overriding-member-function-in-c/
Why not use the image as a resource? I believe most projects for most compilers search within the project's folder so that should be a good place for the image; correct?
I'd still say use the image as a resource or if you're still stubborn enough, place it in the IDE's folder?
What am I doing wrong? In the following templated functions, I'm trying to convert all my CopyMemory functions to std::copy functions.
I'm not sure what I'm doing wrong as they don't work as they should with the std::copy but instead, they work with memcpy and CopyMemory. I'm only doing it to understand how to use std::copy on arrays and pointers rather than plain iterators.
template<typename T>
void S(unsigned char* &Destination, const T &Source)
{
//CopyMemory(Destination, &Source, sizeof(T));
std::copy(&Source, &Source + sizeof(T), Destination); //Fails..
Destination += sizeof(T);
}
template<typename T>
void D(T* &Destination, unsigned char* Source, size_t Size)
{
CopyMemory(Destination, Source, Size);
Source += sizeof(T);
}
template<typename T>
void D(T &Destination, unsigned char* Source, size_t Size)
{
CopyMemory(&Destination, Source, Size);
Source += sizeof(T);
}
I've also figured that I could do the following to convert iterators to pointers:
std::string Foo = "fdsgsdgs";
std::string::iterator it = Foo.begin();
unsigned char* pt = &(*it);
How would I convert pointers to iterators then? :S
I find it funny that you complain about lack of C++ "support" by the POSIX libraries, then turn around and compare it to the Win32 API (itself a C interface).
But at least it's widely documented and doesn't have a horrible naming convention. I've never seen Dirent.h or any of those includes before.
Welcome to multi-platform
Things that are not specified by the standard (such as directory traversal) are left to system implementors.
That explains it! I'll come up with my own implementation or just use boost like ancient dragon suggested.
Hmm I was really hoping to not have to add anything extra but if that's the only way then I guess I'll have to do that.
Why is there so little support for plain C++ on linux though? :S
Why is C++ on linux basically C? I've tried everything to avoid C on linux but it's simply near impossible. I've tried to stick directly to the standard library but I somehow find myself using dirent.h, types.h, etc..
Is there any other ways to do these other than using C or WinAPI? Or am I just going to have to live with it and merge both of them using #ifdef _WIN32? I'm using Ubuntu 12.04 with g++ and Codeblocks. There's barely any documentation of programming c++ on linux :S I've searched and every time I end up at stackoverflow or "Linux equivalent of..". For bitmaps, I had to create all the structures, types, etc.. There has to be an easier way than this?
Anyway is there any other way to do this with just c++?
#include <stdio.h>
#include <dirent.h>
int listdir(const char *path) {
struct dirent *entry;
DIR *dp;
dp = opendir(path);
if (dp == NULL) {
perror("opendir: Path does not exist or could not be read.");
return -1;
}
while ((entry = readdir(dp)))
Result.push_back(entry->d_name);
closedir(dp);
return 0;
}
Versus:
std::vector<std::string> SearchDirectory(std::string RootDirectory, std::string FileExtension, bool SearchSubdirectories, bool FullPath, bool IncludeFolders)
{
std::vector<std::string> FilesFound; // Result
std::string FilePath; // Filepath
std::string Pattern; // Pattern
std::string Extension; // Extension
HANDLE hFile; // Handle to file
WIN32_FIND_DATA FileInformation; // File information
Pattern = RootDirectory + "/*.*";
hFile = FindFirstFile(Pattern.c_str(), &FileInformation);
if(hFile != INVALID_HANDLE_VALUE)
{
Repeat
if(FileInformation.cFileName[0] != '.')
{
FilePath.erase();
FilePath = (FullPath ? RootDirectory + "/" + FileInformation.cFileName …
Ahh but if I do that, what happens when I access the values in the body?
Rectangle(int width = 0, int height = 0, int x = 0, int y = 0) : width(width), height(height), x(x), y(y)
{
x = 500; //does it assign to the x within the class? Does it assign to the parameter x?
y = 500;
Point(x, y); //which x/y does it use? How will the compiler know which is which? do I use this.x?
}
Perfect! I ended up doing:
std::copy(reinterpret_cast<unsigned char*>(&bFileHeader), reinterpret_cast<unsigned char*>(&bFileHeader) + sizeof(BITMAPFILEHEADER), BmpBuffer.begin());
//Etc.. etc..
Had to cast to get it to work. None the less, everything works fine now. Thank you lots!
Is there a way to do the following better? Current I write a set of pixels to a file called "PngFile.bmp". Then I read that file back in as a PNG encoded buffer.. Then I save that buffer back to the harddisk and delete "PngFile.bmp"
/*std::fstream PngFile(TempPath, std::fstream::out | std::fstream::app | std::ofstream::binary);
if (!PngFile.is_open()) return false;
PngFile.write(reinterpret_cast<char*>(&bFileHeader), sizeof(BITMAPFILEHEADER));
PngFile.write(reinterpret_cast<char*>(&Info.bmiHeader), sizeof(BITMAPINFOHEADER));
PngFile.write(reinterpret_cast<char*>(&TEMP[0]), Size());
PngFile.close();
*/
//I do not want to write it to a physical file.. Maybe if I can write it to a memory location.. Maybe write it to a vector of unsigned chars.
//There has to be a better way to do the following?..
unsigned w = 0, h = 0;
std::vector<unsigned char> bmp(sizeof(BITMAPFILEHEADER) + sizeof (BITMAPINFOHEADER) + Size());
unsigned char* Ppos = &bmp[0];
memcpy(Ppos, &bFileHeader, sizeof(BITMAPFILEHEADER)); //copy the file header into the vector.
Ppos += sizeof(BITMAPFILEHEADER);
memcpy(Ppos, &Info.bmiHeader, sizeof(BITMAPINFOHEADER)); //copy the info header into the vector.
Ppos += sizeof(BITMAPINFOHEADER);
memcpy(Ppos, &TEMP[0], Size()); //copy/append the vector of pixels into the vector.
std::vector<unsigned char> image, png;
if (DecodeBMP(image, w, h, bmp) || lodepng::encode(png, image, w, h)) return false;
lodepng::save_file(png, FilePath);
remove(TempPath);
So my question is.. Is there a better way to do the above? Currently I dislike having to do memcpy on a vector tbh. But then again, I'm not sure of any other way to do it. I tried using an iterator but it errors out since I actually created the iterator and it points to nothing + sizeof(...). I cannot enter values instead for std::copy.. …
#include <windows.h>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int Die_1 = 0, Die_2 = 0;
void RollDice()
{
Die_1 = (rand() % 6 ) + 1;
Die_2 = (rand() % 6 ) + 1;
}
int ComputerRolls()
{
RollDice();
return (Die_1 + Die_2);
}
int UserRolls()
{
char UserInput = 0;
std::cout<<"Press two to roll"<<std::endl;
cin>> UserInput;
cin.ignore();
if (UserInput == '2')
{
RollDice();
std::cout<<"You Rolled: "<<Die_1<<" And: "<<Die_2<<std::endl;
std::cout<<"For a grand total of: "<<Die_1 + Die_2<<std::endl;
return (Die_1 + Die_2);
}
return -1;
}
void WinnerResult(int UserResult, int ComputerResult)
{
if (UserResult == ComputerResult)
{
std::cout<<"You Tied with the computer!"<<std::endl;
}
else if (UserResult > ComputerResult)
{
std::cout<<"You Won!"<<std::endl;
}
else
std::cout<<"You Lost! The computer rolled a grand total of: "<<ComputerResult<<std::endl;
}
int main()
{
WinnerResult(UserRolls(), ComputerRolls());
}
I'm learning several languages. 5 at once but I took a liking to one specific feature of java. The This keyword.
From their tutorial:
/*Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this*/
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
//but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Why can't we do this in C++? The compiler says it's ambiguous or that the parameter x shadows a member of such and such class.
Is there any tricks to doing this?
Also another thing I'd like to know:
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, …
I tried that.. It didn't work. The solution was to change:
WinDEP = -static -static-libgcc -static-libstdc++ -shared -s -o
//AND
$(WinDIR)/$(WinOUT): $(ObjFiles)
@echo
@echo "Linking Object Files.."
@mkdir -p $(WinDIR)
@$(WinGPP) -Wl,$(SrcDIR)/OpenGL32.def $(WinDEP) $(WinDIR)/$(WinOUT) $(ObjFiles) -lgdi32 -lglu32 -lopengl32
But now it warns me of:
Warning: resolving _GLHook_wglSwapLayerBuffers by linking to _GLHook_wglSwapLaye
rBuffers@8
Warning: resolving _GLHook_wglSwapMultipleBuffers by linking to _GLHook_wglSwapM
ultipleBuffers@8
Warning: resolving _GLHook_wglUseFontBitmapsA by linking to _GLHook_wglUseFontBi
tmapsA@16
Which isn't a problem but it is really really annoying. Anyway to hide that?
So I've started learning makefiles today for a project I've been working on. The project uses OpenGL and GDI. I decided to dive right into make files and so far, everything compiles but at the very end, it gives a bunch of undefined references. Thing is, when compiled in codeblocks, the project compiles just fine! I decided to learn make files just for the sake of learning it but now I cannot figure out what I did wrong at all :S I'd like someone to take a look at it and maybe help me on what I'm doing wrong please.
The errors I get is as follows (below it has my makefile):
obj/Calculations.o:Calculations.cpp:(.text+0x3d7): undefined reference to `glGet
Integerv@8'
obj/Calculations.o:Calculations.cpp:(.text+0x3f0): undefined reference to `glGet
Doublev@8'
obj/Calculations.o:Calculations.cpp:(.text+0x409): undefined reference to `glGet
Doublev@8'
obj/Calculations.o:Calculations.cpp:(.text+0x465): undefined reference to `gluPr
oject@48'
obj/Calculations.o:Calculations.cpp:(.text+0x50c): undefined reference to `gluPr
oject@48'
obj/Calculations.o:Calculations.cpp:(.text+0x572): undefined reference to `glGet
Integerv@8'
obj/Calculations.o:Calculations.cpp:(.text+0x58b): undefined reference to `glGet
Doublev@8'
obj/Calculations.o:Calculations.cpp:(.text+0x5a4): undefined reference to `glGet
Doublev@8'
obj/Calculations.o:Calculations.cpp:(.text+0x6a3): undefined reference to `gluUn
Project@48'
obj/Calculations.o:Calculations.cpp:(.text+0x7db): undefined reference to `gluUn
Project@48'
obj/Commands.o:Commands.cpp:(.text+0x115): undefined reference to `wglGetCurrent
DC@0'
obj/Commands.o:Commands.cpp:(.text+0x12b): undefined reference to `GetDeviceCaps
@8'
obj/Commands.o:Commands.cpp:(.text+0x1bb): undefined reference to `CreateFontA@5
6'
obj/Commands.o:Commands.cpp:(.text+0x1d3): undefined reference to `SelectObject@
8'
obj/Commands.o:Commands.cpp:(.text+0x22b): undefined reference to `SelectObject@
8'
obj/Commands.o:Commands.cpp:(.text+0x239): undefined reference to `DeleteObject@
4'
obj/Commands.o:Commands.cpp:(.text+0x260): undefined reference to `glDeleteLists
@8'
obj/Commands.o:Commands.cpp:(.text+0x2d4): undefined reference to `glGetIntegerv
@8'
obj/Commands.o:Commands.cpp:(.text+0x38f): undefined reference to `glGetIntegerv
@8'
obj/Commands.o:Commands.cpp:(.text+0x3c4): undefined reference to `glGetIntegerv
@8'
obj/Commands.o:Commands.cpp:(.text+0x4b0): undefined reference to `glColor4f@16'
obj/Images.o:Images.cpp:(.text+0xa90): undefined reference to `DeleteDC@4'
obj/Images.o:Images.cpp:(.text+0xaa1): undefined reference to `DeleteObject@4'
obj/Images.o:Images.cpp:(.text+0x1202): undefined …
Not sure why the above suggestions were sprintf :S
string VariableString = "gsdgdsghas";
string FilePath = "test/" + VariableString + ".txt";
ofstream write(FilePath.c_str());
If you take a look, on lines 207 and 208 in Logger.cpp I immediately call OpenLogFile, and due to the mutex the file_map[prefix] has to exist.
Don't think that's what he meant?
Try:
void Logger::CloseLogFile(const std::string& prefix)
{
std::map<std::string, FileInfo*>::iterator it = file_map.find(prefix);
delete file_map[prefix];
file_map.erase(it);
}
Maybe file_map[prefix];
doesn't exist or points to an invalid memory location?
Also are you sure you don't have to do: file_map[prefix].ofs.close()
.. Then delete?
Uhh I just solved it! LOL such a humilating mistake ={
const unsigned char* BuffPos = reinterpret_cast<const unsigned char*>(&Pointer);
changed to:
const unsigned char* BuffPos = reinterpret_cast<const unsigned char*>(Pointer);
It's the address of that was messing it up.
Info Member Variable is defined as BITMAPINFO. Pixels is a vector of RBGA struct which looks like.
typedef union RGB
{
uint32_t Color;
struct
{
unsigned char B, G, R, A;
} RGBA;
} *PRGB;
I cannot seem to debug it because it's built into a DLL. The DLL is then loaded by another program (Java program).
At most it gives me:
#
A fatal error has been detected by the Java Runtime Environment:#
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x685cfaf0, pid=4892, tid=3348#
JRE version: 7.0Java VM: OpenJDK Client VM (21.0-b17 mixed mode windows-x86 )Problematic frame:C [OPENGL32.dll+0x8faf0]#
Failed to write core dump. Minidumps are not enabled by default on client versions of Windows#
If you would like to submit a bug report, please visit:The crash happened outside the Java Virtual Machine in native code.See problematic frame for where to report the bug.#
--------------- T H R E A D ---------------
Current thread (0x1ae62800): JavaThread "Thread-6" daemon [_thread_in_native, id=3348, stack(0x23170000,0x23370000)]
siginfo: ExceptionCode=0xc0000005, reading address 0x00000000
Registers:
EAX=0x00000001, EBX=0x2336eef4, ECX=0x00000001, EDX=0x22fc38fe
ESP=0x2336ee64, EBP=0x00000000, ESI=0x00000000, EDI=0x22fc38fe
EIP=0x685cfaf0, EFLAGS=0x00210297Top of Stack: (sp=0x2336ee64)
0x2336ee64: 2336eef4 00000042 685fdbc0 685c2ae7
0x2336ee74: 00000200 68601bff 00000000 2336eef0
0x2336ee84: 00000001 00000001 00000000 685ba555
0x2336ee94: 2336eef4 00000000 00000001 00000014
0x2336eea4: 2336efcc 2336ef14 5051ff01 2336eef0
0x2336eeb4: 2336eef0 00000000 2336eef0 685682da
0x2336eec4: 2336eef0 00000000 00000001 ffffffff
0x2336eed4: ffffffff 00000030 6ca5e930 00000000Instructions: (pc=0x685cfaf0)
0x685cfad0: 38 7f dc …
I've been trying to do this for some time. I can do it with a vector but with a const void*, it crashes badly!
My bad code:
Bitmaps::Bitmaps(const void* Pointer, int Width, int Height, uint32_t BitsPerPixel)
{
Pixels.clear();
memset(&Info, 0, sizeof(BITMAPINFO));
width = Width; height = Height;
size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
Info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
Info.bmiHeader.biWidth = width;
Info.bmiHeader.biHeight = height;
Info.bmiHeader.biPlanes = 1;
Info.bmiHeader.biBitCount = BitsPerPixel;
Info.bmiHeader.biCompression = BI_RGB;
Info.bmiHeader.biSizeImage = size;
bFileHeader.bfType = 0x4D42;
bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(Info.bmiHeader);
bFileHeader.bfSize = bFileHeader.bfOffBits + size;
const unsigned char* BuffPos = reinterpret_cast<const unsigned char*>(&Pointer);
height = (height < 0 ? -height : height);
Pixels.resize(width * height);
for (int I = 0; I < height; I++)
{
for (int J = 0; J < width; J++)
{
Pixels[(height - 1 - I) * width + J].RGBA.B = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.G = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.R = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.A = (Info.bmiHeader.biBitCount > 24 ? *(BuffPos++) : 0);
}
if(Info.bmiHeader.biBitCount == 24)
BuffPos += width % 4;
}
}
My good code:
Bitmaps::Bitmaps(std::vector<unsigned char> &Pointer, int Width, int Height, uint32_t BitsPerPixel)
{
Pixels.clear();
memset(&Info, 0, sizeof(BITMAPINFO));
width = Width; height = Height;
size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
Info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
Info.bmiHeader.biWidth = width;
Info.bmiHeader.biHeight = height;
Info.bmiHeader.biPlanes = 1;
Info.bmiHeader.biBitCount = BitsPerPixel;
Info.bmiHeader.biCompression …
Yeah but it's not the path to the process I want. It's the process ID. I can compile my code into a .so? How do I get this shared library thing?
The reason I want the PID is because if one application has many instances, the paths will all be the same. The PID is the only way I can think of to distinguish which one ran it.
How can I get a DLL's Parent Window Title? OR How can I get the PID of the process that loaded my DLL?
I need this so I can make a file for each process that loads my DLL but the file has to contain some sort of identifier. Something like File.PID.
I decided to use Process ID because I want to do this in a portable way. Is there any portable ways to get the PID that loaded my dll?
Also is there a way I can program for linux on windows? Basically I want to see if a linux system will run my dll (even though I didn't have any ifdef __linux). I'd like to make my DLL run on both windows and linux.
Hello everyone. I have a problem with my checksum and logic. I wrote a program that downloads and read bitmaps and try to generate a checksum for each one. The checksum is used as the name to save the bitmap as so that I don't save the same bitmap every time. The problem is that the RGB values of the images change ever so slighlty every time (Un-noticed by my eyes). Because of this, I decided to use the alpha values to generate unique values inorder to not save the same images over and over. Thing is, with this method.. Two images with the same amount of alpha values will have the same checksum and that's bad for me.
My checksum is as follows:
DWORD CheckSum(const void* Data, size_t Width, size_t Height, uint32_t BitsPerPixel)
{
DWORD CheckSum = 0;
const unsigned char* BuffPos = static_cast<const unsigned char*>(Data);
Height = (Height < 0 ? -Height : Height);
for (size_t I = 12; I < Height; I++) //Has to start at 12.
{
for (size_t J = 0; J < Width; J++)
{
BuffPos+=3;
CheckSum += (BitsPerPixel > 24 ? *(BuffPos++) : 0);
}
if (BitsPerPixel == 24)
BuffPos += Width % 4;
}
return CheckSum;
}
Is there anyway I can still generate unique checksums but at the same time keep it static per image so that I don't end up saving and downloading the same image more than once? I was thinking that I'd have to find the …
Happens to all of us. It depends on the settings. Visual studio defaults to unicode so every string is prefixed with an L.
A couple other stuff like suffix _s. strcpy would be strcpy_s, vsprintf would be vsprintf_s.. etc..
Visual studio code compiles in codeblocks most of the time but the other way around doesn't work any time at all. Well for me.
I usually do:
#ifdef _MSC_VER
vsprintf_s(........);
#else
vsprintf(....);
#endif
Don't use conio. Also use a vector as the array isn't contingously aligned. A nice constructor to allow dynamic sizing. Also if you wanted it to continously add 10, you have to store the value it was currently at, add 10 to it and add 10 to the initial. I rewrote the loop for you. You can probably change it to (int J = 1 + Old; J <= Old + 10; ++J); same thing -- one less variable.
#include <iostream>
#include <vector>
class abc
{
public:
struct st
{
int num;
int val;
};
std::vector<st> arr;
abc() {}
abc(int Amount) : arr(Amount) {}
void funct();
};
void abc::funct()
{
int Old = 0, L = 10, K = 0;
for(int I = 1; I <= 2; ++I)
{
for(int J = 1 + Old; J <= L; ++J)
{
arr[K].num = I;
arr[K].val = J;
++K;
}
Old += 10;
L += 10;
}
}
int main()
{
abc z(21);
z.funct();
for (int I = 0; I < 21; ++I)
{
std::cout<<"Num: "<<z.arr[I].num<<std::endl;
std::cout<<"Val: "<<z.arr[I].val<<std::endl;
}
return 0;
}
I'm ignoring the ones that say:
Warning: resolving _GLHook_wglUseFontOutlinesW by linking to _GLHook_wglUseFontOutlinesW@32
It's because I'm using a def file. Either way, that's the only warnings I get. The resolving ones (this doesn't happen in msvc with the exact same code so that's why I ignored it). It works fine on ATI/Radeon Cards. I'm just not so sure why it does this on intel & nvidia.
But what if it's not zero AND it points to invalid memory?
I haven't thought of that situation but I'm pretty sure that it's NOT allowed to point to invalid memory at all. Infact I'm 100% sure of that because that function tells opengl where to grab the data to draw the next model AND I'm intercepting it right before.
It points to valid memory most of the time. It can be null but I've already checked previously if it is, still the same behaviour when it's not. The size can be 0 at times but I've ran 10,000 tests and it has only ever been 0 once. I also tried checking for 0 size but it makes no difference, it still gives a random value.
I've also tried (Makes the program crash instantly):
DWORD Crc32::Calculate(void *pData, size_t length)
{
return Crc32::Calculate(pData, length, 0);
}
DWORD Crc32::Calculate(void *pData, size_t length, DWORD initialRemainder)
{
static const DWORD lookupTable[256] =
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
0xF762575D, 0x806567CB, …
Why does my checksum not work? I use it on my computer with ATI graphics and it works perfectly fine. When I switch to a computer with Intel graphics, it starts doing random values and they aren't the same. I switch back to my comp, the values are still the same (Static.. Never changes).
At first I thought maybe it's an endian problem but I used (Returns Little Endian):
#include <iostream>
#include <windows.h>
using namespace std;
std::string GetEndianness(void)
{
union
{
uint8_t c[4];
uint32_t i;
} u;
u.i = 0x01020304;
if (0x04 == u.c[0])
return "Little Endian.";
else if (0x01 == u.c[0])
return "Big Endian;";
else
return "Unknown Endian;";
}
int main()
{
std::cout<<GetEndianness();
}
My CheckSum:
DWORD Hook_CheckSum(DWORD *BufferData, int Size)
{
if(!BufferData) return 0x0;
DWORD Temp = 0, Sum = *BufferData;
for(int I = 1; I < (Size / 4); I++)
{
Temp = BufferData[I];
Temp = (DWORD)(Sum >> 29) + Temp;
Temp = (DWORD)(Sum >> 17) + Temp;
Sum = (DWORD)(Sum << 3) ^ Temp;
}
return Sum;
}
My Usage:
DLL_EXTERN void __stdcall HookglBufferDataARB(GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage)
{
Buffer.Pointer = data;
Buffer.CheckSum = CheckSum((DWORD*)data, size);
BufferList.push_back(Buffer);
(*orig_glBufferDataARB) (target, size, data, usage);
}
Is there a special case that I'm missing where my checksum will not work? Why only my computer sees it correctly? Anyone have a better idea of what I should use? I'm generating ID's for models. I use the algorithm on the vertex …
Try exporting with /MT enabled.
Solved.. For anyone with this problem, the solution was:
template<typename T>
void MemDeSerialize(std::vector<T> &Destination, unsigned char* &Source, size_t Size)
{
Destination.resize(Size);
for (size_t I = 0; I < Size; ++I)
{
T* Object = &Destination[I]; //Using a temporary object fixes it.
MemDeSerialize(Object, Source, Size);
}
}
It's to use a temporary object.