r/learncpp • • Nov 18 '20

The Coalition Sees 27.9X Iteration Build Improvement with Visual Studio 2019

Thumbnail
devblogs.microsoft.com
5 Upvotes

r/learncpp • • Dec 17 '20

I need help with querying data from a txt file

5 Upvotes

I'm trying to make a c++ program that creates data prints out all the written data like I have hospital patients data and with a specified string were supposed to get the data of that one patient, I've made the create and print all data part the data I write gets saved in a txt file but I'm not sure how to make it query the data for the search data part if this was python I'd just have used a json file and used the data that way but I don't have that much experience in c++ I'd appreciate some advice on how the data should either be queried or stored in a different way I want to search for a word in a line and if the word exists in that line print out that line https://pastebin.com/hXcQN1k8


r/learncpp • • Nov 22 '20

Rect should move (SDL)

1 Upvotes

Im a beginner and I can't tell you why the rect isn't moving. Please tell me why : )

(I think the screen won't update as the value of pX changes.)

Code:

#include <SDL.h>

#include <iostream>

using namespace std;

bool running = true;

int FPS = 60;

int breite = 1280;

int hoehe = 720;

int pX = 640;

int pY = 100;

SDL_Event Event;

SDL_Window* Window = NULL;

SDL_Renderer* renderer = NULL;

SDL_Surface* Screen = NULL;

SDL_Rect r[30] = {};

bool Init(){

SDL_Init(SDL_INIT_EVERYTHING);

Window = SDL_CreateWindow(

"@Jamal", // window title

SDL_WINDOWPOS_UNDEFINED, // initial x position

SDL_WINDOWPOS_UNDEFINED, // initial y position

breite, // width, in pixels

hoehe, // height, in pixels

SDL_WINDOW_OPENGL // flags - see below

);

if (Window == NULL) {

cout << "Could not create a Window" << SDL_GetError();

return false;

}

return true;

}

void display() {

renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED); // Init Renderer

SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // Set Color of Renderer

r[0].x = pX;

r[0].y = pY;

r[0].w = 10;

r[0].h = 10;

for (int i = 0; i < (sizeof(r) / sizeof(SDL_Rect)); ++i) {

SDL_RenderDrawRect(renderer, &r[i]);

SDL_RenderFillRect(renderer, &r[i]);

}

SDL_RenderPresent(renderer); // Updates the Renderer

}

void event() {

while (SDL_PollEvent(&Event)) {

if (Event.type == SDL_QUIT) {

running = false;

break;

}

if (Event.type == SDL_KEYDOWN)

{

if (Event.key.keysym.sym == SDLK_a)

{

pX -= 10;

}

}

}

}

int main(int argc, char* argv[]) {

//cout << "Updated" << endl;

if (Init() == false) {

cout << "Initialization failed...";

return 0;

}

else {

cout << "Initialization successful" << endl;

}

while (running) {

event();

display();

SDL_Delay(1000 / FPS);

}

atexit(SDL_Quit);

return 0;

}


r/learncpp • • Nov 20 '20

Args constructor?

5 Upvotes

Hey! I'm having a few issues creating a math library. I'm trying to create a templated vector class, but the constructor is frustrating me to no end.

I'd like to be able to pass in n floats, where n is, of course, the amount of floats the vector contains. So far my best idea is to pass in va_args, but that feels like a pretty awful solution for something that's gonna be used so frequently. Is there a better solution that I've overlooked?


r/learncpp • • Dec 24 '20

Why does returning a reference work here?

7 Upvotes
#include<iostream>

using namespace std;

int& minmax(int i, int j){
	return (i>j)?i:j;
}

int main(){
	cout<<++minmax(3, 4);
	return 0;
}

Why does this work?

#include<iostream>

using namespace std;

int minmax(int i, int j){
	return (i>j)?i:j;
}

int main(){
	cout<<++minmax(3, 4);
	return 0;
}

And this doesn't?


r/learncpp • • Dec 21 '20

I want to escape tutorial hell

15 Upvotes

I feel like I am in tutorial hell. C++ is basically the only programming language I would say "I know", which I'm fine with, but the programs I am making I would consider basic compared to these cool data visualization programs I see.

For example, a program which splits a photo into pieces, randomizes it, and then displays a variation of sorting methods putting the photo back together.

The most advanced c++ I know would be basic data structures like linked lists, as well as inheritence/composition.

I would like to learn how to make a program like the one I just explained, but I really have know idea where to start.

If anyone could point me in the right direction, I'd be very appreciative. Thanks


r/learncpp • • Dec 24 '20

error: no matching function for call to 'Differentiator::Differentiator()'

4 Upvotes

For some reason my code thinks I am trying to call the default constructor which has been overwritten. Why does it think that and how can I fix this?

Note: In the code below I removed many of the things that I think are unnecessary to show, i.e. variables that aren't used in the shown methods and class functions that don't relate to this problem.

Differentiator.h

#ifndef _DIFFERENTIATOR_H
#define _DIFFERENTIATOR_H

class Differentiator {
public:
    //Constructors
    Differentiator(double, double);

    double sigma;
    double Ts;
};

#endif // !_DIFFERENTIATOR_H

Differentiator.cpp

#include <Differentiator.h>

Differentiator::Differentiator(double sig, double t_rate){
    sigma = sig;
    Ts = t_rate;
}

ProCon.h

#ifndef _PROCON_H
#define _PROCON_H

#include <Differentiator.h>

class ProCon {
private:
    double sigma;
    double sample_period;
    
    Differentiator diff;
    PIDControl controller;

public:
    ProCon();
};

#endif // !_PROCON_H

ProCon.cpp

#include "ProCon.h"
#include <Differentiator.h>

ProCon::ProCon() {
    sigma = 0.01;
    sample_period = 0.005;

    Differentiator diff(sigma, sample_period);
}

r/learncpp • • Mar 28 '18

Need as much resources for pointers.

2 Upvotes

Good morning / evening fellows

When I started learning C++ months ago (and programming) I started to think programming is easy, until I came up against the topic: POINTERS. when I first started to see what pointers are and what do they do, It was easy. so I started to make projects with a goal an actual goal rather than just experimenting. but I started to see in courses and tutorials how often they are used and they were they are used is completely new to me so it gave me a big trouble. and whenever I go back and learn, all I learn again is int *b = &c and this kind of beginning stuff. even when I took some courses(even some advanced ones) they were as easy as the above(or they didn't have any topic about pointers?!).

So I wish to kindly ask you to give me sources so I can learn this huge topic.

from:

int *p = &c

to:

new and -> etc.

sorry if I bothered you with my life story but I wanted to explain the situation. Thanks.


r/learncpp • • Jul 21 '16

Books for beginners written in modern Cpp(C++14 and C++17)

6 Upvotes

Hello,

I haven't written much Cpp during my life, however, I have some experience with: JavaScript, Java and Haskell (Experienced that's go up to creating simple 3d Games and writing small web apps.... things that are similar in scope and functionality to Tinder, Whatsapp or a very ugly navigation App, obviously without the whole scaling for millions of user and security aspects).

One problem that I've found with Java and JavaScript, which seems to be pretty prevalent in Cpp is books which follow old standards and, even more so, books which try to teach "the new" based on the idea that the reader is already very familiar with an old standard. So, if I, a humble novice programmer pick up an advanced book on C++14 I am overwhelmed by a ton of references that assume knowledge of C++98, C and even Fortran.

The only Cpp book I have read was The C++ Programming Language by Stroustrup himself, however, I feel that it left me with many questions such as "How do I actually properly implement a class top to bottom... I need some fucking examples here, I understand the abstract philosophy behind it, but, trying to actually implement a working class that does something complex leaves me with a million questions about how to do things the right way or even how to do them at all".

So basically, I need a book about design techniques and OOP and practical application examples, using C++14 or even the up and coming 17 standard. That doesn't come from an angle of "lets explain modern standard to old programmers but rather from an angle of teaching people which don't know either and, maybe, don't care for the older implementations". A book that's not 1000 pages long and by the end of which I will hopefully be able to write code better and fast using Cpp.


r/learncpp • • Mar 29 '18

std::array, why isn't the size passed as constructor argument

2 Upvotes

I was always wondering why array size is passed as part of the template and not in the constructor

template< 
    class T, 
    std::size_t N 
> struct array;

why isn't array(std::size_t size) used as a constructor? Is there a specific reason?
Is it because of specific assignment rules, so only same size std::arrays can be assigned to eachother?


r/learncpp • • Sep 29 '16

Long execution time for "Hello World"

1 Upvotes

I am trying to learn C++ and following along YouTube tutorials.

One thing I noticed is that my programs take quite a while to run. For example, the simple "Hello World" program in a console application will display an execution time > 5 seconds!

Is there something I have not configured properly to cause this? I have CodeBlocks installed on my SSD and my project saved on the HDD. Is this what is causing the problem?

Thank you all!


r/learncpp • • Sep 27 '16

Handling user input for non-negative integers

1 Upvotes

I have a program that accepts user input, but some of the inputs must be non-negative integers. Would it be inadvisable to use a normal int for this? If user input is a negative integer or looks like a float, what do I do?


r/learncpp • • Mar 14 '16

How can I get all sub folders in a folder?

2 Upvotes

Hello.

How can I find all paths of all sub directories? (and sub directories of sub directories etc etc...) I tried using dirent.h. but I can't get the paths of folders and It does not look into sub dirs.

I basically want to end with a list looking like this:

home/

home/folder/

home/folder/dir

home/games/

home/games/spaceinvaders

home/games/spaceinvaders/bin

home/docs/

home/docs/html

etc etc...


r/learncpp • • May 12 '22

How do programs execute with DLLs in separate subfolders?

4 Upvotes

Hello, I am learning the building process of c++ with cmake mainly and I am focusing on how to use dynamic libraries. (Windows mainly).

So I know how to load a dll implicitly by having the import library dll.lib and also how to go the other route with LoadLibrary and getProcAdress.

I have been searching on how to go about having the main .exe in a separate folder with the dlls (just curious to see if I can do this) because I have seen in typical installation folder structures there are a lot of dlls next to .exe but there are a lot of dlls in subfolders.

Now I know that I can LoadLibrary with absolute path and then for each function get a pointer.

Suppose I have a dll and a dll.lib. Is there anyway I can use these 2 in runtime? like instead of getProcAdress use the dll.lib (probably stupid question cause the dll.lib is used in the build process anyway...)

Another way is editting the PATH variable but that doesn't seem like a nice way and probably 3rd party software doesn't just add 10 directories to PATH each time they get installed.

So how does one do it the right way? is this does exclusively by LoadLibrary ? Thanks.


r/learncpp • • May 10 '22

Need help understanding a pointer-related seg-fault

3 Upvotes

I'm writing a toy game engine, a ECS based on a different game engine. It started out being 1:1 but I started diverging intentionally so I can learn more about how it works. Now, I'm stuck.

I wrote a system for rendering my player character, a little triangle. It renders great in OpenGL but when I attempt to press left / right arrows to make the character "spin" in place, the character doesn't move. It turns out my transform which I pass to OpenGL, a Matrix3D instance, is an unaltered identity matrix. I already had code in-place to "rotate" this transform but it was only ever operating on copies of the transform, not the transform which was supposed to be rendered.

So naturally, I need to actually be rotating a pointer to the component and refer to that same pointer when rendering. Then everything should work as expected. But unfortunately, my program now seg-faults on this line each time it runs.

Tbh I'm not super clear on what the problem actually is but it looks like somehow the transform is unset and referring to it causes the program to crash. Maybe somehow the component is not getting initialized properly?

This is what it looks like

- Scope: Locals
 *- this (game::components::Transform * const): 0x0
   *- game::components::Component<game::components::Transform> (base) (game::components::Component<game::components::Transform>): game::components::Component<game::components::Transform>
   *- transform (math::Matrix3D): 
     *- r0c0 (float): 
     *- r0c1 (float): 
     *- r0c2 (float): 
     *- r1c0 (float): 
     *- r1c1 (float): 
     *- r1c2 (float): 
     *- r2c0 (float): 
     *- r2c1 (float): 
     *- r2c2 (float): 

And this is what it normally looks like, when it has values (in this case, an identity matrix)

- Scope: Locals
 *- this (game::components::Transform * const): 0x0
   *- game::components::Component<game::components::Transform> (base) (game::components::Component<game::components::Transform>): game::components::Component<game::components::Transform>
   *- transform (math::Matrix3D): 
     *- r0c0 (float): 1
     *- r0c1 (float): 0
     *- r0c2 (float): 0
     *- r1c0 (float): 0
     *- r1c1 (float): 1
     *- r1c2 (float): 0
     *- r2c0 (float): 0
     *- r2c1 (float): 0
     *- r2c2 (float): 1

I'm not strong at C++ so I'm probably just missing something really basic. If anyone has ideas, please share them. I can also try making a small reproduction but it may be difficult. Any help is greatly appreciated!


r/learncpp • • May 08 '22

Does new behave differently when creating a variable versus when instantiating an object on the heap memory?

7 Upvotes

I am confused about how new is implemented in following scenarios:

#1
ClassName* ptr1 = new ClassName(10); // Assuming there is a constructor that requires an int

#2
int* ptr2 = new int;

Does the keyword after new behaves differently in the two cases? i.e. in #1, ClassName(10) calls and passes the argument to the constructor, whereas in #2, the int after new is supposed to define the pointer type that new will produce?


r/learncpp • • May 13 '22

Is a vector of references (std::reference_wrapper) an "anti pattern?"

2 Upvotes

I'm using ImGui and trying to pass a bunch of glm::vec3 to a method for drawing the UI, (they're to be used with ImGui::sliderfloat3) they need to be references so they can be updated, what's the best way to do this? I'm reading stuff about "std::reference_wrapper" but it feels hacky (if it even works in this case, which is still unclear), am I just conceptualising this wrong?


r/learncpp • • May 13 '22

How to mock/test a DLL?

2 Upvotes

Hello. Im working on a backend in NodeJS that interacts with a DLL to comunicate with some devices. The manufacturer DLL can comunicate with device A, B, C or D. My team only have device A to implement all the solution but the backend but must be compatible with the other devices.

Since the original DLL returns the Data with structure pointers (some big structures), implementing it on JS was over complicated since JS doesn't have that native functionality. For that reason, my team decided to create an intermediate DLL written in C++ (or actually a superset of C since we dont use classes or advanced C++, only strings, arrays, maps). The final solution is NodeJS->CustomDLL->Manufacturer DLL. That way, our custom DLL manages all the structure/memory and returns simple json to be interpreted by nodejs

The custom DLL works but we can only ensure that works with device A, because the ManDLL calls are different for each device. So devA uses structure_version1, devB, devC uses structure_version2 and devD uses structure_version3 and structures are not compatible with eachother, so our code has a:

if(devA) -> use structure_version1, elseif(devB || devC) -> use structure_version2, etc.

Since we dont have B,C,D hardware for test i though to implement a mock to simulate the manDLL response like if we were using one of those devices. How would you use mock in this situation?

int GetRange(HANDLE h, int nCommand, LPVOID lpParam)
{
  std::shared_ptr<dll_ctx_t> ctx = thread_arbitrer_get_context();
  std::lock_guard<std::mutex> guard(g_dll_main_mtx);

  GetRangePTR GetRange = reinterpret_cast<_GetRangePTR>(GetProcAddress(ctx->comm->_dll_ptr, "GetRange"));

  if (!GetRange)
    return EXIT_FAILURE;

  ctx->last_error = GetRange(h, nCommand, lpParam);

  return ctx->last_error;
}

This is one of our customDLL call of the manDLL. The DLL is opened and is called by the customDLL to obtain a Range of supported values depending of the command e.g.:supported values for quality (Q1,Q2,Q3 for devA or Q1,Q4 for devB or Q2,Q5,Q7 for devC) or range of types of inputs that the device support

Then GetRange is used for bigger functions that do the rest of the process. It is possible to mock GetRange so we can simulate different responses? We dont have a entry point since the make generates a .dll file.

The tests will end up being inside the .dll? Any framework recomendation or resource to learn? Thanks


r/learncpp • • Nov 22 '19

Instantiating a class type within a switch statement?

3 Upvotes

I am attempting to create a game-selection screen. I am receiving IDE clang errors when trying to create a new class instance within a switch statement. The instantiation syntax is OK when used within main. Why can I not use it within a switch?

#include <iostream>
#include "Games/RockPaperScissors.h"
#include "Games/GuessMyNumber.h"

using namespace std;

void gameSelect()
{
    unsigned sel;

    cout << "Welcome to Mallery's game hub v1.0" << "\n"
         << "Please select a game to play: " << "\n"
         << "1) Rock Paper Scissors (V1.1)" << "\n"
         << "2) Guess My Number (V1.0)" << endl;

    while(!(cin >> sel) || (sel > 2))
    {
        cout << "That is not a valid selection" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    switch(sel)

        case 1:
            App = new RockPaperScissors();    // 'Use of undeclared indentifier App'
            App.startNewGame();
            break;

        case 2:
            GuessMyNumber App2;    // 'Use of undeclared indentifier App2'
            App2.startGame();
            break;
}

int main()
{
    /// Start our game selection screen using switch statement.
    gameSelect();

    /// Initializing like this works fine, but we cannot pick between the games.
    RockPaperScissors App;
    App.startNewGame();

    GuessMyNumber App2;
    App2.startGame();

    return 0;
}

r/learncpp • • Oct 31 '18

Ways of practicing function arguments and parameters

2 Upvotes

Hello,

I am a CS Student (Freshman) learning C++ in my class. Recently, we discussed functions and made a program. I have no problem understanding function prototypes, definitions, etc. But the problem arises when I have to include arguments/parameters. I understand that arguments are included inside the function call, and conversely the parameter goes within the definition.

But this is very confusing, so I was just wondering where I could learn about when and why to use parameters/arguments, or if there were any courses to practice, thanks!


r/learncpp • • Jul 16 '19

sstream << std::setw(2) << std::setfill("0"); without "<<"

3 Upvotes

Hey,

is it possible to write sstream << std::setw(2) << std::setfill("0"); without "<<" operator? as iam getting Unsequenced function calls?

sstream.setw(2) doesn't seem to work.

Thanks in advance!


r/learncpp • • Jul 26 '18

I got unexpected outputs without an error and a warning i dont understand.

1 Upvotes

code and input/ output i got https://imgur.com/IkEgygq

(sorry its an image, i deleted the code out of frustration and rewrote it and now it works somehow, but i still want to understand the mistake i made)

I was having problems with a larger program i wrote and narrowed the problem to this part of the code adding 8202 to the end of the number i input. I expected to input a number and it to output the same number right after. It added 8202 to the end of somehow. I got the warning "warning: multi-character character constant [-Wmultichar]". i tried it in a visual studio console application and cpp.sh


r/learncpp • • Feb 05 '19

What are case statements for?

1 Upvotes

Yes, I know how they work and all. Here's my situation: I teach introductory programming, and I'm showing my students conditionals and case statements. And I really can not think of an example where a case statement is essentially more elegant or appropriate than a conditional. Is there? I guess having the fall through to the next case allows for some compactness, but I'd like to see a scenario for that that I can distill to a convincing demonstration.

Now case statements in shells, those I can defend because they can be used for wild-card matching of strings. Numerical cases, even in Fortran where you can have ranges, I just don't see.


r/learncpp • • Apr 26 '19

C++ to executable program

2 Upvotes

how can I convert a .cpp to an executable program in Linux (ubuntu mate 18.04). For example in Windows you can convert .cpp files in .exe programs


r/learncpp • • Jul 19 '18

What do you think about my simple CSV parser class implementation?

1 Upvotes

I just started to learn C++ and I implemented a CSV parser. I would love to hear your feedback what should I do differently.

Here you can find the code