C++ program to dump a boiler plate C++ - 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;
}

Related

VS code set up for c++

I am new in VS code. I wrote a C++ code like one below. but unfortunately in the terminal or output panel I cannot get both of the string and variable value. in the terminal only variable's inputted value is showing. How to fix this?
#include <bits/stdc++.h>
int main()
{
int slices;
std::cin >> slices;
std::cout << "You got " << slices << " of pizzas" << std::endl;
return 0;
}

Using header files correctly

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/

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.

c++ string concatenation second time

I am a newbie, writing a c++ code to open and read from multiple files and then dump part of the data into other files.
I want to generate file names in a for loop.
But I can't concatenate string(numbering of file) and string literal(a file extension). The same line of code works at the very beginning of the program, but not at the later part.
int main(int argc, char *argv[])
{
std::cout << std::string("9") + ".dat" << std::endl;
// many more lines
dump = 1;
if (dump == 1){
for (int ilevel=std::max(levelmin,lmin); ilevel < lmax + 1; ilevel++){
std::cout << std::string("9") + ".dat" << std::endl; // crashes here!
std::ofstream fout (std::string("9") + ".dat", std::ios::out | std::ios::binary);
std::cout << grid[ilevel].cube[0] << std::endl;
fout.write ((char*)&grid[ilevel].cube[0], grid[ilevel].cube.size() * sizeof(grid[ilevel].cube[0]));
fout.close();
}
}
...
}
If I put std::cout << std::string("9") + ".dat" << std::endl; at the beginning, it works and prints "9.dat".
but in the later loop, segmentation fault.
In between I call a function that uses stringstream to pad leading zeros to an integer. The function looks:
std::string int2str(const int n, const int m){
std::stringstream ss;
ss << std::setfill('0') << std::setw(m) << n;
std::string s2(ss.str());
ss.clear();
return s2;
}
I don't have a clear understanding about string and stringstream in c++.
But out of many things in my program, this function is the only thing I can think of being relevant. Other parts of codes does not deal with strings. It's mostly array manipulation code.
I've also tried std::string("9") + std::string(".dat")
but had no luck.
What is wrong?
Is there a specific reason why you're using std::string("9") rather than just "9"?
Where does the 9 come from? If its generated as part of a loop or a returned value from a function you can either place the variable itself to be concatenated, or the function that returns it, so:
std::cout << iFileNumber + ".dat" << std::endl;
or
std::cout << fileNumberGenerator() + ".dat" << std::endl;
For the hardcoded examples you've provided, I personally can't see the need for anything other than
std::cout << 9 + ".dat" << endl;
but that could easily just be lack of experience on my part.
For the sake of printing to the command line, its also worth nothing that this is equally acceptable syntax (assuming you're not already aware):
std::cout << 9 << ".dat" << endl;

"Roll-Back" or Undo Any Manipulators Applied To A Stream Without Knowing What The Manipulators Were [duplicate]

This question already has answers here:
Restore the state of std::cout after manipulating it
(9 answers)
Closed 4 years ago.
If I apply an arbitrary number of manipulators to a stream, is there a way to undo the application of those manipulators in a generic way?
For example, consider the following:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Hello" << hex << 42 << "\n";
// now i want to "roll-back" cout to whatever state it was in
// before the code above, *without* having to know
// what modifiers I added to it
// ... MAGIC HAPPENS! ...
cout << "This should not be in hex: " << 42 << "\n";
}
Suppose I want to add code at MAGIC HAPPENS that will revert the state of the stream manipulators to whatever it was before I did cout << hex. But I don't know what manipulators I added. How can I accomplish this?
In other words, I'd like to be able to write something like this (psudocode/fantasy code):
std::something old_state = cout.current_manip_state();
cout << hex;
cout.restore_manip_state(old_state);
Is this possible?
EDIT:
In case you're curious, I'm interested in doing this in a custom operator<<() I'm writing for a complex type. The type is a kind of discriminated union, and different value types will have different manips applied to the stream.
EDIT2:
Restriction: I cannot use Boost or any other 3rd party libraries. Solution must be in standard C++.
Yes.
You can save the state and restore it:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
std::ios state(NULL);
state.copyfmt(std::cout);
cout << "Hello" << hex << 42 << "\n";
// now i want to "roll-back" cout to whatever state it was in
// before the code above, *without* having to know what modifiers I added to it
// ... MAGIC HAPPENS! ...
std::cout.copyfmt(state);
cout << "This should not be in hex: " << 42 << "\n";
}
If you want to get back to the default state you don't even need to save the state you can extract it from a temporary object.
std::cout.copyfmt(std::ios(NULL));
The standard manipulators all manipulate a stream's format flags, precision and width settings. The width setting is reset by most formatted output operations anyway. These can all be retrieved like this:
std::ios_base::fmtflags saveflags = std::cout.flags();
std::streamsize prec = std::cout.precision();
std::streamsize width = std::cout.width();
and restored:
std::cout.flags( saveflags );
std::cout.precision( prec );
std::cout.width( width );
Turning this into an RAII class is an exercise for the reader...
Saving and restoring state is not exception-safe. I would propose to shuffle everything into a stringstream, and finally you put that on the real stream (which has never changed its flags at all).
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
std::ostringstream out;
out << "Hello" << std::hex << 42 << "\n";
std::cout << out.str();
// no magic necessary!
std::cout << "This should not be in hex: " << 42 << "\n";
}
Of course this is a little less performant. The perfect solutions depends on your specific needs.
Boost IO State saver might be of help.
http://www.boost.org/doc/libs/1_40_0/libs/io/doc/ios_state.html
I know that is an old question, but for future generations:
You can also write a simple state saver yourself (it will certainly help you avoid leaving the state changed). Just use the solution suggested by #loki and run it from the constructor/destructor of an object (in short: RAII) along these lines:
class stateSaver
{
public:
stateSaver(ostream& os): stream_(os), state_(nullptr) { state_.copyfmt(os); }
~stateSaver() { stream_.copyfmt(state_); }
private:
std::ios state_;
ostream& stream_;
};
Then, you will use it like this:
void myFunc() {
stateSaver state(cout);
cout << hex << 42 << endl; // will be in hex
}
int main() {
cout << 42 << endl; // will be in dec
myFunc();
cout << 42 << endl; // will also be in dec
}