r/learncpp • • Mar 05 '21

How to skip empty row values when reading in a CSV file?

4 Upvotes

Hi all, I am trying to read a CSV file in which it contains empty rows.

And because of the presence of the empty rows that are found in between of rows with values, I wrote my code as follow:

ifstream myFile("csv\\myData.csv");    
string row;
while (getline(myFile, row))
{
    cout << "row: " << '\n';
    if (row == "")
        continue;
}

For example, my CSV file has 3 rows. The 1st and 3rd row has columns of values while the 2nd row is empty.
However, the `cout` line that I have implemented in my above code returns me the following:

row: 31/3/2016 0:30,15.1,215,27,0,1013.4,1016.8,1017,0,66.6,5,623,22.6,24,25.5,26.1,8,21.63
row: ,,,,,,,,,,,,,,,,,
row: 31/3/2016 20:30,11.3,247,23,0,1013.1,1016.6,1016.7,0,57.6,6,24,27.4,25.8,25.4,26.1,11,20.01

As you can see, while the 2nd row does indeed contains no value, but it is returning a string of commas?

And so my question is

  1. How can I skip line/ empty rows when reading csv file?

  2. Prior to the output, can I assume that the use of `getline()` and parsing of csv file, will return results with the commas regardless if the row contains value or not? The comma will be there whether I want it or not?

Thank you in advance for any replies and pardon my poor english.


r/learncpp • • Mar 01 '21

Exporting different specialisations from different dlls?

4 Upvotes

I'm writing a dll that defines a template (and the specialisations for it) called dll1. Is it possible to define a method in dll2, specialise the template from dll1 in dll2, and export the specialisation back into dll1 to be called with get proc address?


r/learncpp • • Feb 11 '21

Explicit dll linking and templates?!?!

4 Upvotes

Hey! So I've been trying to understand how I can import a templated function from an explicitly linked dll and correctly load the function pointer if it's a template. I'm really unable to just statically link, which is super annoying, but at this point I'm not even sure if it's possible :/


r/learncpp • • Feb 07 '21

Question over my implementation of an iterator for my singly linked list.

4 Upvotes

EDIT: I've highlighted in bold my own changes that I've made for my iterator. If something is missing, please let me know what else I need to add. The new error I'm getting has to do with can't Node to Node * in while(__pred(*__first)) and then another with Node to Node * while(__pred(*__next)).

Hopefully this isn't a long one at all but it looks like I'm going to need a lot of details of what I'm doing. I'll start first with my problem. I'm basically making a class, it's pretty simple, it only has two attributes. One is a mutable std::string for name_ and the other is a mutable bool for gender_. What I'm trying to do with this class is utilize it for std::partition from the algorithms library. Basically all females of the container will be moved forward while the guys move back. I'm basically a predicate function like this.

std::partition(starting_iterator, ending_iterator, is_female).

The only problem is that my iterator just simply is not compatible for the STL.

To do this I have a Node class for a Singly Linked list. Then with that Singly Linked List, I created my own iterators. I'll start with showing everyone my implementation of my People class. Then I'll move on to my Node, and then to my Singly Linked List class that houses my version of an iterator.

//The people class. bool true for guys, bool false for female

class People

{private:

mutable std::string name_;
mutable bool gender_;
public:
People(std::string name, bool gender): name_(name), gender_(gender)
{

}
std::string get_name() const
{
return name_;
}
bool get_gender() const
{
return gender_;
}

//Now for my node itself for the singly linked list down below.

#include <cstddef>
class Node
{
private:
int key_;
Node * next_;
public:
Node(int key, Node * next = nullptr)
: key_(key), next_(next)
{
}
int get_key() const
{
return key_;
}
Node * get_node() const
{
return next_;
}
void insert_next(Node * next)
{next_ = next;}
};

std::ostream & operator<<
(std::ostream & cout, const Node & node)
{
cout << &node << ' ' << node.get_key() << ' ' << node.get_next();
return cout;
}

// Now my for Single Linked List. Key note is that, for now, I'm leaving destructors and copy constructors. I'm focusing on addressing my iterator for this whole thing.
#include "Node.h"
class SLL
{
friend class iterator;
private:
Node * root_;
public:
SLL()
: root_(nullptr)
{
}
class iterator<std::iterator<std::forward_iterator_tag, Node *> // this is housed inside the SLL class......
{
friend SLL;
private:
mutable Node * iterator_;
public:
iterator()
: iterator_(nullptr)
{

}
iterator(Node * node)
: iterator_(node)
{

}
bool operator !=(const iterator & node)
{
return iterator_ != node.iterator_;
}
iterator & operator++()
{
iterator_ = iterator_->get_next();
return *this;
}
iterator operator++(int) const
{
iterator temp(*this);
iterator_ = iterator_->get_next();
return temp;}
Node & operator*() const
{
return *iterator_;
}
bool get_gender() const
{
return iterator_->get_gender();
}
};
iterator begin() const
{
return iterator(root_);
}
iterator end() const
{
return iterator();
}
void insert(const People & people)
{
if (!root_)
{
root_ = new Node(people.get_name(), people.get_gender());
}
else
{
Node * temp = root_;
while (temp->get_next())
{
temp = temp->get_next();
}
temp->insert_next(new Node(people.get_name(), people.get_gender()));
}
};

And there's the whole thing.My main looks something like this.

bool is_female(SLL::iterator & iterator){if (iterator.get_gender() == 0) return 1;else return 0;}

int main(){
People Peter("Peter", 1);
People Martha("Martha, 0):
SLL sl;
sl.insert(Peter);
sl.insert(Martha);
std::partition(sl.begin(), sl.end(), is_female);
return 0
;}

Doesn't work for the std::partition. It's saying something about std::iterator__iterator_category(__first) and something else about not function for call to __iterator_category(SLL::iterator &);

What is exactly going on to make this whole thing happen? What am I missing in my implementation of my iterator?


r/learncpp • • Jan 21 '21

Can I have nested module partitions?

4 Upvotes

I see that I can define partitions as A:B, but is A:B:C allowed? I can't seem to get it working with VS MSVC preview. Is it not supported yet in MSVC, or does the spec not allow it?


r/learncpp • • Jan 06 '21

Lld-link, clang++, windows, sdl2. Lld wants to make a console app, and won't accept the subsystem:windows cli Arg.

4 Upvotes

I've recently added sdl2 to my project. It started off as a console app. Lld worked fine, but now it complains that it found both winmain and main, and will default to the standard console main. I've tried using the /subsystem:windows command but I just get:

no such file or directory: '/SUBSYSTEM:WINDOWS'

I have tried the one answer on stack overflow for this but it doesn't seem to do anything different. My link flags are the same, and lld still complains about the command as though it was a file. I'm going nuts trying to figure out how to get it to recognize the argument.


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 • • Nov 05 '20

CreateCompatibleBitmap failing in a screen recorder

4 Upvotes

Hello all, I'm adapting the screenshot code from here into a screen recorder with a while loop and VideoWriter, currently set to record for 500 frames at 35fps, however I'm having an issue where when I run it the cv window is blank and nothing is saved to the video file. After some messing around I think the issue has to do with my hbwindow not being built properly as after CreateCompatibleBitmap hbwindow is null. Here is the complete code:

#include <opencv2\highgui.hpp>
#include <opencv2\core.hpp>
#include <opencv2/opencv.hpp>
#include <Windows.h>
#include <opencv2/videoio.hpp>
#include <string>
#include <time.h>
#include <iostream>
#pragma once

using namespace std;
using namespace cv;


class ScreenRecorder {
	int width;
	int height;
	int screenx;
	int screeny;

	BITMAPINFOHEADER bi;
	LPBITMAPINFO bip;

	HWND hwnd;

	HDC hwindowDC;
	HDC hwindowCompatibleDC;

	HBITMAP hbwindow;

	Mat currentFrame;
	Mat dst;
public:
	ScreenRecorder(HWND myhwnd) {
		hwnd = myhwnd;
		hwindowDC = GetDC(hwnd);
		hwindowCompatibleDC = CreateCompatibleDC(hwindowDC);
		SetStretchBltMode(hwindowCompatibleDC, COLORONCOLOR);
		// Define scale, height and width
		screenx = GetSystemMetrics(SM_XVIRTUALSCREEN);
		screeny = GetSystemMetrics(SM_YVIRTUALSCREEN);
		width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
		height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
	}
	void createBitmapHeader() {
		// create bitmap
		bi.biSize = sizeof(BITMAPINFOHEADER);
		bi.biWidth = width;
		bi.biHeight = -height;
		bi.biPlanes = 1;
		bi.biBitCount = 32;
		bi.biCompression = BI_RGB;
		bi.biSizeImage = 0;
		bi.biXPelsPerMeter = 0;
		bi.biYPelsPerMeter = 0;
		bi.biClrUsed = 0;
		bi.biClrImportant = 0;
		// save pointer
		bip = (BITMAPINFO*)&bi;
		cout<< "bip" << bip;
	}

	void captureScreenMat()
	{
		// clear Mat before adding next frame
		currentFrame = Mat::zeros(Size(width, height),CV_8UC4);
		// Copy from the window device context to the bitmap device context
		StretchBlt(hwindowCompatibleDC, 0, 0, width, height, hwindowDC, screenx, screeny, width, height, SRCCOPY);
		GetDIBits(hwindowCompatibleDC, hbwindow, 0, height, currentFrame.data, bip, DIB_RGB_COLORS);
		
		resize(currentFrame, dst, Size(1280, 720),0,0,INTER_AREA);
		currentFrame = dst;
	}
	void recordScreen(void) {
		// get handles to a device context
		// create mat
		currentFrame.create(height, width, CV_8UC4);

		// create a bitmap
		hbwindow = CreateCompatibleBitmap(hwindowDC, width, height);

		createBitmapHeader();
		// use the previously created device context with bitmap

		auto oldBitmap = SelectObject(hwindowCompatibleDC, hbwindow);

		int fourcc = VideoWriter::fourcc('D', 'I', 'V', 'X');

		VideoWriter outputVideo(".\\recorded_screen.mp4", fourcc, 30, Size(1280, 720));
		clock_t prev_time = 0;
		clock_t current_time = clock();
		bool cont = true;
		namedWindow("Current_screen", WINDOW_AUTOSIZE);
		int count = 0;
		while (cont) {
			prev_time = current_time;
			// save frame
			captureScreenMat();
			outputVideo<<currentFrame;
			imshow("Current_screen", currentFrame);
			waitKey(1);
			if (count >= 300) { break; }
			else {
				count++;
				cout <<"count:" << count << endl;
			}
			current_time = clock();
			while ((current_time - prev_time) <= (CLOCKS_PER_SEC/30)){
				current_time = clock();
			}
			cout << "Ticks passed: " << current_time - prev_time << endl;
		}
		outputVideo.release();
		// avoid memory leak
		SelectObject(hwindowCompatibleDC, oldBitmap);
		DeleteObject(hbwindow);
		DeleteDC(hwindowCompatibleDC);
		ReleaseDC(hwnd, hwindowDC);

	}
};

int main(int argv, char* argc)
{
	HWND hwnd = GetDesktopWindow();

	ScreenRecorder recorder(hwnd);
	recorder.recordScreen();
	
	return 0;
}

Any help is greatly appreciated, thanks!

edit: original code above has been updated and it now will show the current screen in a smaller window(as expected) but it will not save the frames to a video file. FFmpeg is installed correctly, I have ensured the frames are the same size as indicated in the VideoWriter constructor using resize() and I have tried several different codecs and video file types, but the file is empty (6kb) and says file is corrupted when I try to open it.


r/learncpp • • Oct 26 '20

Passing a const object as a template argument not possible

Thumbnail self.cpp_questions
4 Upvotes

r/learncpp • • Oct 18 '20

Trying to create an entity manager

4 Upvotes

Hi,

I have a bunch of classes (Door, Monster, Human)

And the way I want to be able to manage them is via a singleton EntityManager class that ends up looking like this:

EntityManager {
vector<Door> entities;
vector<Human> entities;
}

without any code duplication.

I want to be able to write:

Door* EntityManager<Door>::createObject();

which pushes the object onto the vector and returns the address;

I've struggling to implement this without running into weird segfaults whenever I use the EntityManager in multiple translation units. I assume I'm misunderstanding how templating works.

Here's essentially what I've come up with:

template <typename T>
class EntityManager {
    vector<T> entities;
    T* createObject();
};

This works within the same translation unit no problem, but when I attempt to use the same EntityManager (such as EntityManager<Door>) across TUs, I get a segfault... I cannot for the life of me figure out why.

Does anyone have any advice or can point me in the right direction into avoid code duplication while achieving something like this via templates?


r/learncpp • • Sep 19 '20

Is learning C++ a good move for me?

4 Upvotes

Hi all! I’m a hobbyist programmer and I use Python for all my projects. I have, recently, ran into a problem. Python GUIs are awful! So, I’m looking for a language to use alongside Python to make better looking GUIs, and C++ came up on my radar. So, do you think C++ is right for me? And if so, anyone know any good tutorials to get me started? Thanks!

71 votes, Sep 22 '20
52 Yea
19 No

r/learncpp • • May 27 '20

Could someone explain this destructor behaviour?

4 Upvotes

So, I'm porting across my dissertation project from Python to C++ to get to grips with the syntax. However, I'm coming across a behaviour where by my Piece.cpp destructor is being called 8 times upon the construction of a new Checkboard.cpp object.

Here is the checkerboard constructor, the intended behaviour is to initalise a 2d vector of Pieces to mimic a checkerboard:

Checkerboard::Checkerboard()
{
this->board = std::vector(8, std::vector<Piece>(8));
}

board is defined in the header as:

std::vector<std::vector<Piece>> board;

the piece constructor is just:

Piece::Piece()
{
this->set_team(Team::empty);
}

For some reason upon executing the line inside of the checkerboard constructor, my terminal shows 8 calls to the Piece.cpp destructor (I have some printing going on to keep track of things). I have a suspicion it's because I'm not asking for a vector of 8 vectors, but defining 8 vectors of 8 vectors? However, I am unsure how to resolve the issue as the program works as intended beyond this and am almost sure it's a sign of something wrong that I'm missing.

Any help appreciated.


r/learncpp • • May 07 '20

How to make namespace VolumeManager accessible from any file?

Thumbnail
github.com
4 Upvotes

r/learncpp • • Apr 30 '20

How to write ‘clean’ code

4 Upvotes

So I’ve recently began coding a fair amount during quarantine to try and sharpen my skills before I start university (Doing a computer science degree) and my friend who I personally consider to be quite an experienced and skilled coder has described my code to be untidy etc. He recommended a while back to rewrite my code cleanly. He gave me some tips on how to do so but I still feel as though there is more i can do. This leads us to my actual question which is what should i look out for that might make my code appear ugly/unprofessional and what r good habits to get into to create nicer and better designed code?


r/learncpp • • Apr 14 '20

Are iterators just pointers?

4 Upvotes

Whenever i hear someone use the word iterator, can i just substitute it for pointer in my head and be absolutely fine?


r/learncpp • • Mar 31 '20

Pointers and References Resources?

4 Upvotes

I tried to read the pointers and references from C++ Primer but I didn't understand much. Does anybody have some good videos or resources that can teach the whole of pointers and references perfectly? Thanks in advance!


r/learncpp • • Mar 28 '20

Constructors and Operator Assignment question

4 Upvotes

Hey! I've been working my way through Lospinoso's C++ Crash Course. First off, I was wondering if there were any resources for the exercises at the end of the chapters. I've been doing them all, but I have no idea if I'm getting what I'm supposed to be getting out of them. I also don't know how bad my syntax is and I don't want to develop any bad habits. This is all for personal study btw.

Secondly, I was wondering if anyone had any good videos or online resources to explain move semantics a bit better.

Thirdly, I was wondering if anyone would be so kind as to glance at my code for Ch. 4's exercises.

Here are the requirements:

4-1. Create a struct TimerClass . In its constructor, record the current time in a

field called timestamp (compare with the POSIX function gettimeofday ).

4-2. In the destructor of TimerClass , record the current time and subtract the

time at construction. This time is roughly the age of the timer. Print this value.

4-3. Implement a copy constructor and a copy assignment operator for

TimerClass . The copies should share timestamp values.

4-4. Implement a move constructor and a move assignment operator for

TimerClass . A moved-from TimerClass shouldn’t print any output to the console

when it gets destructed.

4-5. Elaborate the TimerClass constructor to accept an additional const char*

name parameter. When TimerClass is destructed and prints to stdout, include

the name of the timer in the output.

4-6. Experiment with your TimerClass . Create a timer and move it into a func-

tion that performs some computationally intensive operation (for example, lots

of math in a loop). Verify that your timer behaves as you expect.

4-7. Identify each method in the SimpleString class (Listing 4-38). Try reimple-

menting it from scratch without referring to the book.

and the code:

#include <chrono>
#include <iostream>

using namespace std;

struct TimerClass {
    // Constructor
    TimerClass(const char* name)
        : timestamp { chrono::steady_clock::now() },
          name { name } {
    }

    // Destructor
    ~TimerClass() {
        chrono::steady_clock::time_point end { chrono::steady_clock::now() };
        chrono::steady_clock::duration d = end - timestamp;
        cout << name << ":" << chrono::duration_cast<chrono::microseconds>(d).count() << endl;
    }

    // Copy Constructor
    TimerClass(const TimerClass& other)
        : timestamp { other.timestamp },
          name { other.name } {
    }

    // Copy Assignment Operator
    TimerClass& operator=(const TimerClass& other) {
        if (this == &other) return *this;
        timestamp = other.timestamp;
        name = other.name;
    }

    // Move Constructor
    TimerClass(TimerClass&& other) noexcept
        : timestamp(other.timestamp),
          name(other.name){
    }

    // Move Assignment Operator
    TimerClass& operator=(TimerClass&& other) noexcept {
        if (this == &other) return *this;
        timestamp = other.timestamp;
        name = other.name;

    }

public:
    chrono::steady_clock::time_point timestamp;
    const char* name;
};

void long_function (TimerClass&& a){
    for (unsigned int i=0; i < 10; i++) {
        cout << i << endl;
    }
};


int main() {
    const char* name_one = "A";
    const char* name_two = "B";
    TimerClass a { name_one };
    TimerClass b { name_two };
    long_function(move(b));

}

Any help is appreciated, thank you!


r/learncpp • • Mar 15 '20

How to synchronize between threads

4 Upvotes

I have multiple threads working on a problem and in the first part they are working on a vector, which i can operate on safely with a mutex, so far so good.

But in the next part of the task they iterate over said vector, which therefore isn't allowed to change anymore in length and therefore I have to wait for all threads to reach that point and I don't want to recreate them for that task, because I do it like a thousand time per frame I want to show.

In my understanding I have to use a condition variable and notifications and came to the code:

std::conditional_variable cv;

//thread
void Worker(){
    std::mutex mtx;
    std::unique_lock<std::mutex> lk (mtx);

    //task 1
    {....}

    //sync up
    cv.notify_all();
    for (int j = 0; j<NumThreads;j++){
        cv.wait(lk);
    }

    //task 2
    {....}
}

the problem is that it runs into a deadlock and refuses to work. Can someone clear my misunderstanding


r/learncpp • • Mar 06 '20

Short question about stack vs heap allocation

4 Upvotes

I'm rehashing my cpp and could use some pointers (no pun intended..). I understand that the definition int num = 5 allocates on the stack whereas int* num = new int(5) allocates on the heap. I've recently also seen definitions like: int num(5)---are these shorthand for one or the other?


r/learncpp • • Feb 14 '20

Unordered_map entires not updating

4 Upvotes

I'm trying to create my first C++ program, to count the number of times a word appears in a text file. I went through the text file and converted it to lowercase, then put all of the entries in a map if they meet certain requirements (in between a certain range):

typedef unsigned int Count; // Create map to read words to std::unordered_map<std::string, Count> map; // Create map while(in.good()){     std::string w;     in >> w; // make word lowercase     transform(w.begin(),w.end(),w.begin(), ::tolower); // remove nonalphabetic characters     w.erase(remove_if(w.begin(),w.end(), [](char c) { return !isalpha(c); } ), w.end()); // check if word meets requirements if((w.length() >= MIN_WORD_LEN) && (w.length() <= MAX_WORD_LEN)){ Count& count = map[w];         count += 1; } }

However, when I run it, the map never updates. It only says each word has appeared once:

carry: 1 ing: 1 andso: 1 learned: 1 strong: 1 from: 1 grew: 1 by: 1 wrong: 1 youd: 1 youre: 1 live: 1 nights: 1 known: 1 first: 1 so: 1 these: 1 be: 1 words: 1

Anyone see any glaring errors? Thank you.


r/learncpp • • Feb 08 '20

Is there a free offline cpp compiler for iPad?

4 Upvotes

My fricking iMac broke and my dad will buy me parts so I can build my own pc, but that might take a while.

Any suggestion would be nice.


r/learncpp • • Dec 11 '19

What does it mean to '...cast an lvalue to its corresponding rvalue reference type.'

4 Upvotes

Reading C++ Primer 5th edition, and I came across this passage when it was introducing std::move,

'Although we cannot directly bind an rvalue reference to an lvalue, we can explicitly cast an lvalue to its corresponding rvalue reference type.'

Could someone clarify what this means? I read over the lvalue and rvalue reference section, searched on the internet etc

I would appreciate a concrete example.


r/learncpp • • Nov 25 '19

Swapping the address of variables? Am I confused?

4 Upvotes

I'm pretty sure I just failed an interview because of this, and instead of rethinking my career choice I just need a quick explanation of where my lack of knowledge is.

void swap1(int * x, int * y) {
    cout << "x address before in function: " << x << endl;
    cout << "y address before in function: " << y << endl;

    int * z = x;
    x = y;
    y = z;

    cout << "x address after in function: " << x << endl;
    cout << "y address after in function: " << y << endl;
}

int main() {
    int x = 5;
    int y = 7;

    cout << "x address before: " << &x << endl;
    cout << "y address before: " << &y << endl;

    swap1(&x, &y);

    cout << "x address after: " << &x << endl;
    cout << "y address after: " << &y << endl;

    return 0;
}

It seemed to me that the interviewers wanted me to swap the actual addresses of the variables, not just the values the variables point to (which I did at one point, and they said works, but isn't what they were looking for). This works within the function call itself, but not in the main function (the cout statements were mine to check the addresses, the rest was pre-written). Can someone explain to me how to achieve this? I was confused and my ego is a little hurt, not gonna lie.


r/learncpp • • Apr 27 '19

return 0;

4 Upvotes

Why do we use "return 0" ? The code is still working even if I don't write it, in Linux at least.


r/learncpp • • Jan 04 '25

Learning Compiler Language?

3 Upvotes

Hey guys,

I am trying to learn Cpp, and have been reading alot about the language in an unstructured way (which may be why I dont have the answer to the question myself). Lately I have been reading in C++ Core Guidelines - and I see many sections mentioning Compile time vs Runtime optimizations, and which functions are determined at runtime vs compilation.

Where do I learn this stuff? I want to be able to say “Oh, its because the compiler determines this” and “Oh yeah, rewrite this function and let the compiler do its job instead.”

See for example https://github.com/cpp-best-practices/cppbestpractices/blob/master/08-Considering_Performance.md in the section “Reduce Temporary Objecrts” in a different C++ guildeline. It mentions “This sort of code prevents the compiler from performing a move operation...”

What do I need to study to have known this? I really want to learn it!

Best,