Using header files correctly - c++

I'm trying to expand my C++ game hacking skills as when I was starting (2 years ago) I made a bad decision: continue in game hacking with vb.net instead of learning c++ (as I had some vb.net knowledge and 0 knowledge with other languages)
So, now as the very first steps I have to create my toolkit, where I will be using my own templates:
Nathalib.h (my template with all common functions for game hacking).
#pragma once
#include <iostream>
#include <Windows.h>
#include <string>
#include <TlHelp32.h>
#include <stdio.h>
using namespace std;
DWORD ProcessID;
int FindProcessByName(string name)
{
HWND hwnd = FindWindowA(0, name);
GetWindowThreadProcessId(hwnd, &ProcessID);
if (hwnd)
{
return ProcessID;
}
else
{
return 0;
}
}
Hack.cpp (obviously the cheat, will be different for every game).
#pragma once
#include "pch.h"
#include <iostream>
#include <Windows.h>
#include <string>
#include <Nathalib.h>
using namespace std;
int main()
{
While(True)
{
cout << FindProcessByName("Calculator") << endl;
getchar();
cout << "-----------------------------------" << endl << endl;
}
return 0;
}
Target.cpp (as we're not bad boys, I must provide my own target).
#include "pch.h"
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
#define CHAR_ARRAY_SIZE 128
int main()
{
int varInt = 123456;
string varString = "DefaultString";
char arrChar[CHAR_ARRAY_SIZE] = "Long char array right there ->";
int * ptr2int;
ptr2int = &varInt;
int ** ptr2ptr;
ptr2ptr = &ptr2int;
int *** ptr2ptr2;
ptr2ptr2 = &ptr2ptr;
while(True) {
cout << "Process ID: " << GetCurrentProcessId() << endl;
cout << "varInt (0x" << &varInt << ") = " << varInt << endl;
cout << "varString (0x" << &varString << ") = " << varString << endl;
cout << "varChar (0x" << &arrChar << ") = " << arrChar << endl;
cout << "ptr2int (0x" << hex << &ptr2int << ") = " << ptr2int << endl;
cout << "ptr2ptr (0x" << hex << &ptr2ptr << ") = " << ptr2ptr << endl;
cout << "ptr2ptr2 (0x" << hex << &ptr2ptr2 << ") = " << ptr2ptr2 << endl;
cout << "Press ENTER to print again." << endl;
getchar();
cout << "-----------------------------------" << endl << endl;
}
return 0;
}
I don't know why the header file is not being recognized.
This is the correct way to include header files? Should I create a namespace/class/object for calling it?
It's the correct way creating a header file? Or I should create another kind of project/resource for this purpose?
How should I call my library methods? Like LibraryName.MethodName?
I just come from other languages and some ideas/features are not available in the other languages (that's why I'm interested in this one)
If there's something I forgot to add, please tell me and I will update
Thanks

There are multiple errors - please check your textbook.
You include your own headers with #include "". System headers are included with #include<>
The header file generally contains function declarations. Function bodies go into the corresponding .cpp file.
You call your library functions by their name. If they're in a namespace, that might mean the format is namespacename::functionname(arguments).

There are two ways to include headers, using "" or <>
with <> the file will be searched in the system search path (which is not the $PATH variabel, but the list of paths provided with `-I' together with standard headers already known by compiler) and included if found
with "" the file will be search in the current folder and in the system search path
Assuming your header is in th esame folder of hack.cpp, you should use
#include "Nathalib.h"

First off, your header lacks include guards, #pragma once only works with msvc++.
Your header file is probably not in PATH, so you need to specify it's path relative to your project. If your header file is in the same root as your cpp file, all you need to do is change the include statement for that header file to #include "Nathalib.h" otherwise you'll have to specify the relative path.

To add to other aswers- why you should put declaration of function in .h file, while its definition to .cpp file: Writing function definition in header files in C++
I suggest to find some c++ tutorials for example: http://www.tutorialspoint.com/cplusplus/cpp_functions.htm
You should learn tutorials first, making some exercises on simply code. Personally I prefer check then most simply code for new programming construct. Then more complicated.
After such learning you may use for reference also : http://www.cplusplus.com and https://en.cppreference.com/w/

Related

Simple game database problems

NOTE: I am new to C++ and may do things that are bad practice and if you see that please tell me so I can fix that and please don't be mean. I have only started coding 1-2 months ago. And I am still learning. Please be open to the fact I may not know everything.
This is a console text-based game. It works great! Although, I am creating a feature in it to allow the user to drag and drop any amount of other databases on it to allow database transfers. Although this works fine the problem is that I have a little process it will do to try and make sure none of the info in the databases is the same by placing a number to them,
Example there will be 2 profiles 1 in each file. They are both named main. Then the user drags the second database onto the game and it loads that database into the original one. But now becuase there are 2 SIMILAR profile names it won't be able to differentiate which is which. So then it goes through a little function which scans the database and places a number in front of the copies. Starting at 5 and working its way up. Although this would seem to work and not be that hard to actually do I have hit a problem and I do not know what is wrong. I do know however it is something with how it scans for duplicates. Please help.
I have tried for like a whole day trying different methods or re-writing the code. Google has not revealed a lot to me.
I am using the following libraries in my code. (Some might not be used in the example but tbh I don't remember which is directly used in THIS function).
#include <iostream>
#include <iterator>
#include <cstring>
#include <cmath>
#include <cassert>
#include <string>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <utility>
#include <vector>
#include <array>
#include <functional>
#include <fstream>
Here is the scanning function to make sure there are no duplicate profiles.
Let me explain what happens.
I make a ton of variables which are used in the database. As you can see inside of the database it has a certain order.
Using file stream I access the database. (I have a function which will combine all the databases the user dragged in and the current profiles and data which works just fine).
The pattern in the database looks something like this.
profile_name user_name 100 3 0 0 0 0 knight 1 100 0 0
profile name health etc
If you look at the variables you will see the technical order.
void scanCopy()
{
std::string profile{ "John's_Profile" };
std::string name{ "John_Doe" };
int health{ 0 };
int damage{ 0 };
int gold{ 0 };
int exp{ 0 };
int level{ 0 };
int score{ 0 };
std::string CLASS{ "null" };
int dungeon{ 0 };
int maxHealth{ 0 };
int lives{ 0 };
int kills{ 0 };
std::ifstream in("data/database.txt");
std::vector <std::string> profiles;
int sizeOfVector{ 0 };
while (in >> profile >> name >> health >> damage >> gold >> exp >> level >> score >> CLASS >> dungeon >> maxHealth >> lives >> kills)
{
profiles.resize(sizeOfVector += 1);
profiles.at(sizeOfVector - 1) = { profile };
std::cout << profiles.at(sizeOfVector - 1) << "\n\n";
}
in.close();
for (int loop{ 0 }; loop < sizeOfVector; ++loop)
{
int compare{ loop };
for (int index{ loop }; index < sizeOfVector; ++index)
{
if (compare == index)//meaning they are like at profiles(1)and (1)
continue;
if (profiles.at(compare) == profiles.at(index))
{
std::ofstream out("data/~database.txt", std::ios::app);
in.open("data/database.txt");
int nameIndex{ 5 };
while (in >> profile >> name >> health >> damage >> gold >> exp >> level >> score >> CLASS >> dungeon >> maxHealth >> lives >> kills)
{
if (profile == profiles.at(index))
{
out << profile << nameIndex << " " << name << " " << health << " " << damage << " " << gold << " " << exp << " " << level << " " << score << " " << CLASS << " " << dungeon << " " << maxHealth << " " << lives << " " << kills << " " << std::endl; //Notice at the start profile is put into the database with an extra variable nameIndex to make its name now unique.
++nameIndex;
}
else
{
out << profile << " " << name << " " << health << " " << damage << " " << gold << " " << exp << " " << level << " " << score << " " << CLASS << " " << dungeon << " " << maxHealth << " " << lives << " " << kills << " " << std::endl;
}
}
}
}
}
in.close();
remove("data/database.txt");
in.open("data/~database.txt");
std::ofstream out("data/database.txt", std::ios::app);
//A buffer to copy everything inside a file to a string.
std::string upData((std::istreambuf_iterator<char>(in)),
(std::istreambuf_iterator<char>()));
/////
if (out)
out << upData; //putting everything in the tmp file to the file named database.txt
out.close();
in.close();
remove("data/~database.txt");
in.close();
out.close();
}
The problem is that it does not do its job. It will put numbers by anything. Besides that, it will also seem to overflow or something. What it does is after you already dragged something in, it pretends to work. Then any more input from dragging it does not get scanned. Thing is that everything is copied from the files the user drags from the database to a tmp file. Then the database is deleted and the temp file is renamed to database.txt. The problem is that this whole scan function seems to not be working right and I don't see the problem in it. Does anyone know a good way to do something like this or what the problem is? Thanks!
We really do not need the backstory that this is a game, that users can do XYZ and so on. Please construct a minimal example, as in minimal reproducible example. Often by constructing those, you yourself discover the problem. – Fureeish
Thank you Fureeish. I have found the problem. I was sending the function too many times which wiped the file or it did not scan it all the way. It is hard to explain the real thing I did because it was easy but I can't explain it well.
ALL IN ALL. I examined and found the bug, I was sending it to this function I posted up there too many times. or too little times.

Is there a way I can include my files in C++?

Sorry super noob question. I'm new to C++ and any sort of programming in general but I created these programs to read user input and then read what command and file it is. I want to include file a.h but I'm having trouble with it. It's telling me my function main is redefined but when I take it out it spits out more errors. I'm considering maybe an if else statement? Any advice to get me going?
File name tryout.cpp
#include <iostream>
#include <string.h>
#include "a.h"
using namespace std;
int main()
{
string cmd,command,file1,file2;
cout << "prompt<<";
cin >> cmd;
int len = cmd.length();
int temp = cmd.find('<');
command = cmd. substr(0,temp);
cout << "COMMAND: " << command << "\n";
cout << "File Redirection: " << cmd.at(temp) << "\n";
int temp1 = cmd.find('>');
file1 = cmd.substr(temp+1,temp1-temp-1);
cout << "FILE: " << file1 << "\n";
cout << "File Redirection: " << cmd.at(temp1) <<"\n";
file2 = cmd.substr(temp1+1, len-1);
cout << "File: " << file2 <<"\n";
return 0;
}
File name "a.h"
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string cmd,command1,command2,command3;
cout << "prompt<<";
cin >> cmd;
int len = cmd.length();
int temp = cmd.find('|');
command1 = cmd.substr(0,temp);
cout << "COMMAND: " << command1 << "\n";
cout << "PIPE: " << cmd.at(temp) << "\n";
command2 = cmd.substr(temp+1,len-1);
cout << "COMMAND: " << command2 << "\n";
cout << "PIPE: " << cmd.at(temp) << "\n";
command3 = cmd.substr(temp+2,len-2);
cout << "COMMAND: " << command3 << "\n";
return 0;
}
The ".h" suffix is for a "header" file. If you think of a form letter, say from your cell company, at the top is a bunch of stuff telling you the company name, contact, etc.
A "header file" in C++ is a file that mostly provides definitions, things that you might need to share between multiple ".cpp" files. A ".cpp" file is generally a "compilation unit", a discrete file that the compiler is expected to turn into a similarly named "object file".
So in what you've shown us your division of interest is wrong. You've actually implemented main in the ".h" file.
When the compiler reads your ".cpp" file, it reads in the iostream and string.h headers, and then it reads in a.h, which includes an implementation of main. Then, it returns to processing tryout.cpp where it sees another implementation of main.
Solution: Remove main from a.h.
You cannot have multiple main() functions. When compiling, the C++ complier will take the content of the header files and add them where your #include statement is. If it finds more than one main() function, it does not know where to set the start point for the executable. You will have to rename the header file function to something else. Also note that it is common practice not to include function definitions in header files, rather than to use function declarations and have the definitions in other .cpp or pre-compiled .lib files.
I have found this article to be helpful for learning about how headers work.
You cannot have two main functions. If you want to include your file you should put everything in a function or better build a class.

Update: program shows adress of fstream instead of the text file

I am about to write a program which asks the user if they want to "search or convert" a file, if they choose convert, they need to provide the location of the file.
I do not know why the program shows the address of the file instead of opening it.
Here is my first approach:
#include <fstream>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
char dateiname[64], kommando[64];
ifstream iStream;
cout << "Choose an action: " << endl <<
" s - search " << endl <<
" c - convert" << endl <<
" * - end program" << endl;
cin.getline(kommando,64,'\n');
switch(kommando[0])
{
case 'c':
cout << "Enter a text file: " << endl;
cin.getline(dateiname,64,'\n');
iStream.open("C://users//silita//desktop//schwarz.txt");
case 's': break;
case '*': return 0;
default:
cout << "Invalid command: " << kommando << endl;
}
if (!iStream)
{
cout << "The file " << dateiname << " does not exist." << endl;
}
string s;
while (getline(iStream, s)) {
while(s.find("TIT", 0) < s.length())
s.replace(s.find("TIT", 0), s.length() - s.find("TIT", 3),"*245$a");
cout << iStream << endl;
}
iStream.close();
}
At first you can't compare c-strings using ==. You must use strcmp(const char*, const char*). More info about it you can find there: http://www.cplusplus.com/reference/cstring/strcmp/
For example: if (i == "Konvertieren") must become if(!strcmp(i,"Konvertieren"))
As mentioned in Lassie's answer, you can't compare strings in this way using c or c++; just to flesh it out, however, I'll explain why.
char MyCharArr[] = "My Character Array"
// MyCharArr is now a pointer to MyCharArr[0],
// meaning it's a memory address, which will vary per run
// but we'll assume to be 0x00325dafa
if( MyCharArr == "My Character Array" ) {
cout << "This will never be run" << endl;
}
Here the if compares a pointer (MyCharArr) which will be a memory address, ie an integer, to a character array literal. Obviously 0x00325dafa != "My Character Array".
Using cstrings (character arrays), you need to use the strcmp() function which you will find in the cstring library, which will give you a number telling you "how different" the strings are, essentially giving the difference a numerical value. In this instance we are only interested in no difference, which is 0, so what we need is this:
#include <cstring>
using namespace std;
char MyCharArr[] = "My Character Array"
if( strcmp(MyCharArr,"My Character Array")==0 ) {
// If there is 0 difference between the two strings...
cout << "This will now be run!" << endl;
}
While you are not doing so in your question, If we were using c++ strings rather than character arrays, we would use the compare() method to similar affect:
#include <string>
using namespace std;
string MyString = "My C++ String"
if( MyString.compare("My C++ String")==0 ) {
// If there is 0 difference between the two strings...
cout << "This will now be run!" << endl;
}

C++ program to dump a boiler plate C++

I have a C++ program which dumps out a C++ program. Some of the functions are boiler plate code and certain functions has boiler plate code and code tailored based on a few variables.
A simplified example is presented below:
// Snippet: 1
#include <fstream>
using namespace std;
int main()
{
ofstream fout("output.cc");
// bp() has just boiler plate code
fout << "void bp() {" << endl;
fout << "std::cout << \"Hello World!\" << std::endl" << endl;
// a few hundred lines of C++ code send to fout
fout << "}" << endl;
// mix() has boiler plate + some custom code
int size = 4096;
fout << "void mix() {" << endl;
fout << "char buffer[" << size << "];" << endl;
// a few hundred lines of C++ code send to fout
fout << "}" << endl;
// compile output.cc into *.so and delete output.cc
return 0;
}
The output.cc gets compiled and user gets the *.so file. The user does not have access to output.cc.
I wanted to rewrite this since it is difficult to read the boiler plate code when it is inside fout and having escaped quotes makes it a nightmare. Hence I thought of storing the functions in a separate file. For example have bp() in bp.cc:
// file: bp.cc
void bp() {
std::cout << "Hello World" << std::endl
// a few hundred lines of C++ code
}
Then the main file can be written as
int main()
{
std::ifstream src("bp.cc");
std::ofstream dst("output.cc");
dst << src.rdbuf();
}
In case of mix() I would use the Form-Letter Programming by storing the function mix() in mix.cc.
When the functions bp() and mix() were dumped using fout as in Snippet:1, all I had to do was ship the executable since the Snippet:1 is self-contained. But
If I split the functions into separate files `bp()` into `bp.cc` and `mix()` into `mix.cc` how do I ship it as a single executable? I need to ship `bp.cc` and `mix.cc` along with the executable. I do not want the user to access `bp.cc` and `mix.cc`.
Is there a better way to rewrite the `Snippet:1` than what I have suggested to better suit my needs?
You can use raw string literals and just put the code into one of those:
#include <iostream>
char const source[] = R"end(
#include <iostream>
int main() {
std::cout << "hello, world\n";
}
)end";
int main()
{
std::cout << source;
}

How do I correct "expected primary-expression before...?"

I'm just beginning to program and I have no idea what I'm doing. My professor gave us Program Sets to do and I've completed it, but when I Compile the file I get
" J:\Untitled1.cpp In function `int main()':
"36 J:\Untitled1.cpp expected primary-expression before '<<' token "
Here's the full set, remember now that I'm a beginner:
/** CONCEPTS PROGRAM #1, TEMPLATE
PROGRAM Name: Yay.cpp
Program/assignment:
Description: Finds total
Input(s):
Output(s):
suffering_with_c++
Date of completion
*/
//included libraries
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <time.h.>
#define cls system("cls")
#define pauseOutput system("pause")//
using namespace std;
int main()
{
//variable declaration/initialization
time_t nowIsTheMoment;
time(&nowIsTheMoment);
string dateTime;//
cls;
cout <<"\new live in the moment--only this moment is ours. The Current Date and time is: "
<<ctime (&nowIsTheMoment); << endl;//
cout << "\nMy name is Moe Joe." <<endl;//
cout << endl << "I think Computer Programming with C++ will be a bit more PHUN now!"
<< endl;
dateTime = ctime(&nowIsTheMoment);//
cout << endl << "\nYo ho! I am here now...\n" << endl;
cout << endl << "The Current Date and time is: "
<<dateTime <<endl;//
cout << "\nI know clearly that, if I DO NOT comment my programs/project work thorougly, I will lose substantial points.\n" ;
cout << "\bHere is Pause Output in action....\n" << endl;//
pauseOutput; //
cls;//
return 0;
}
Remove the semicolon on line 36
<<ctime (&nowIsTheMoment); << endl;
^
|
You forgot to #include <string> and qualify string and cout with std::.
Start by removing the . after <time.h> it should probably help. Then you got this
ctime (&nowIsTheMoment); << endl;
which can't compile because << needs a left operand (ie: remove the semi-colon).
I don't mean to be rude, but you should try a little bit harder before asking questions on StackOverflow...