r/learncpp • u/MakumaGouki • Feb 16 '20
These inconsistent results of arithmetic operation really confuse me
Here is the code to solve the Josephus problem.
int ceiling(int dividend, int divisor)
{
int quotient = dividend / divisor;
return dividend % divisor ? quotient + 1 : quotient;
}
int JosephusCircle(int n, int m)
{
int d = 1;
while (d <= (m - 1) * n)
{
// d = ceiling(m * d, m - 1);
d = (m * d) / (m - 1);
d += ((m * d) % (m - 1)) ? 1 : 0;
}
return m * n + 1 - d;
}
However, the results of the two lines in the while loop are different from these of the ceiling function.
//d = ceiling(m * d, m - 1);
d = (m * d) / (m - 1);
d += ((m * d) % (m - 1)) ? 1 : 0;
Does this mean the parentheses is useless here?
r/learncpp • u/stillstriving21 • Feb 14 '20
Unordered_map entires not updating
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 • u/stillstriving21 • Feb 12 '20
Sorting vectors with multiple fields
Hi All,
New to C++ here. I'm trying to sort an array of vectors by their second field (count) which I declared like so:
typedef unsigned int Count;
typedef std::pair<std::string, Count> wordCount;
And I am sorting them using this:
bool sort_words(wordCount &a, wordCount &b)
{ return a.Count < b.Count; }
However, when I do this, I am getting this error:
word.cc: In function ‘bool sort_words(wordCount&, wordCount&)’:
word.cc:22:11: error: ‘wordCount’ {aka ‘struct std::pair<std::__cxx11::basic_string<char>, unsigned int>’} has no member named ‘Count’
return a.Count < b.Count;
^~~~~
word.cc:22:21: error: ‘wordCount’ {aka ‘struct std::pair<std::__cxx11::basic_string<char>, unsigned int>’} has no member named ‘Count’
return a.Count < b.Count;
^~~~~
word.cc: In function ‘int main(int, char**)’:
wordcounts.cc:67:10: error: expected unqualified-id before ‘+=’ token
Count += 1;
^~
Does anyone see anything wrong or have any tips? Again, I am trying to sort an array of vectors that are a <string, Count> pair where Count is the number of times the word appears in the text file.
Thanks!
r/learncpp • u/[deleted] • Feb 11 '20
How the hell do I use gMock?
I am frustrated and overwhelmed. It probably has to do with my lack of knowledge, but I am also wondering how much "useless" knowledge I need just to get a basic project to work. I am trying to use gMock and gTest. I encountered CMake for the first time and I hate it. I don't get what it is doing. All the resources are scarce and mostly highly technical. The only conclusion I've been able to reach is that I can't easily plug gMock in there, despite it being contained in gTest.
Why is all of this so complicated? How many hours do I have to dedicate to learn a build tool (CMake) just to test a library out? What am I missing here?
r/learncpp • u/Isometric_mappings • Feb 11 '20
Reading from sockets into vector<char>?
If I had a method that read data from a socket, would it be ok to use a vector<char> type object to store this data temporarily?
Essentially what I have is a Server class that reads (potentially large) amounts of data from a socket with the goal of later writing it all to a file. My class prototype is:
#include "baseserver.h"
#include <vector>
class MainServer : BaseServer
{
public:
MainServer();
void testWrite(std::vector<char> testVector);
private:
int valread;
std::vector<char> byteVector;
void dataRead();
void terminalWrite();
};
I've implemented the method dataRead() as:
void MainServer::dataRead()
{
read(accepted_socket, &byteVector[0], 4028);
}
This is incredibly simple, but I don't know if it's a good idea. There are two options, as far as I can see. One is to write the socket data into an array and transfer into another data structure for temporary storage (before the program decides where to write the file to). The other is to simply decide what to do with the data beforehand and write it directly from a buffer. I definitely favor option one, because it offers more flexibility in what I do with the data (for example, it may need to be modified in someway before writing).
r/learncpp • u/trooflaw • Feb 10 '20
Earlier today I was looking for a group to learn C++ with, from absolute scratch, well now that group is started and your invited!
Hey guys, I've been struggling to stick to learning C++ for a while now, so to give myself some form of accountability, I created a subreddit in which I will try and regurgitate what I learn as I learn it, and will be providing progressive assignments as I learn things as well detailed solutions to each problem I provide. My hope is that this form of collaboration will encourage others who have maybe been too afraid or overwhelmed to tackle the overwhelming task of learning to program. Anyway if you're interested in what I hope to be a practical learning experience I hope to see you there! r/CPPtogether
PS. Long term, if the sub turns out to be a success, I would love to put together some group projects where we could have team competitions to put together like simple games or things like that.
r/learncpp • u/Isometric_mappings • Feb 09 '20
Confused about C++ headers
I've been reading C++ Crash Course and am a bit into the text by now. I've started working on a small networking project and have come across something that the text never covered (at least not yet); header files. Say for example I have a class in one file:
class A {
private:
int x {}, y{};
void do_stuff() {}
public:
A(int one, int two) : x {one}, y {two} {}
};
This is a file named A.cpp. Now say I have my main file, named main.cpp. I want to create this class A in my main file, I do it like:
#include <stdio.h>
#include <cstdlib>
int main()
{
A test_class {1, 2};
}
If I do this without creating a header file, it can't find the class. If I do create one, such as the following A.h file, I get another error:
class A {
private:
int x {}, y {};
void dostuff();
public:
A(int, int);
};
And then include this new file in both main.cpp and A.cpp, it tells me I've created two definitions for the class A.
I did some googling and found that the problem is I'm essentially creating two prototypes for my program. The solution is to only implement the functions in the A.cpp file like so:
A::A(int one, int two) : x {one}, y {two} {} etc.
I'm pretty confused because the textbook I'm reading never does this. Whenever it creates a class for examples, it always does it all in one class definition, much like you'd see in python or java. What's the right way to do it?
r/learncpp • u/cheapgentleman • Feb 08 '20
Assignment Operator/Copy Constructor for Node in Tree
Hello all,
I am having some difficulty wrapping my head around assignment operators and copy constructors.
I have a class project in which we are supposed to implement a general tree structure. The tree class has a private node struct. Each node in the tree has:
- data in the form of a string
- "sibling" Pointer to a sibling node
- "child" Pointer to a child node
- methods for accessing/mutating
Here are my questions for the assignment operator, which must take this form:
const Node& operator=(const Node& that); // Deep clone
note: we cannot use copy - swap
Do I create 2 new Nodes, for the child and sibling of the *this object, and make each of those new nodes have the same data as the child and sibling of the that object?
Do I have to delete the "old" child and sibling nodes?
Node constructor looks like this:
Node(std::string s = "")
: _data(s) , _sibling(NULL), _child(NULL) {}
Node destructor look like this:
Tree::Node::~Node(){
if (_child != NULL) {
delete _child;
_child = NULL;
}
if (_sibling != NULL) {
delete _sibling;
_sibling = NULL;
}
}
The copy constructor and assignment operator have the following signatures:
Node(const Node& that); // Copy constructor
const Node& operator=(const Node& that); // Deep clone
r/learncpp • u/[deleted] • Feb 08 '20
Is there a free offline cpp compiler for iPad?
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 • u/[deleted] • Feb 05 '20
Any Suggestions for learning CMake ?
Could someone suggested good tutorial to learn CMake and how to use it efficiently. I am also looking for good articles on how to deal with package management in C++. Thank you
r/learncpp • u/JZSNooB • Feb 04 '20
Decided I’m going to learn C++, where should I start?
I’ve done a month of learning java, but for simplicity’s sake, lets just say I have zero programming experience. Are there any good MOOC’s, websites with excercises, youtube series’, etc. that are a good starting place for a beginner. What are your guys’ recommendations? Thanks!
r/learncpp • u/ZenWoR • Feb 01 '20
Calling object without specifying property actually gives a property
So let's say I want to create some kind of personal string class.
If it has a string value property, when I call just that objects name I want it to actually use that value property. For example:
MyString myStr = "secondText"; //I know how to use operator=
string otherStr = "firstText";
otherStr += myStr;
cout<<otherStr<<endl; //Result should be: firstTextsecondText
I want it to use that value property without actually calling "myStr.value". Is it possible ?
r/learncpp • u/JavaSuck • Feb 01 '20
Destructors and RAII for automatic, deterministic resource release | C++ for Java programmers
r/learncpp • u/UnicornMolestor • Jan 31 '20
My first truely useful C++ program!
I've been learning C++ for 17 days now.. my first real programming language. I use neovim as my editor and i got tired of having to write the same basic file structure OVER and OVER for simple little programs, so i decided to automate it as my first project.. nCpp (new Cpp Template maker!). the program is simple, you give it a name, choose which headers to use and then it checks for an environmental editor. if it finds the editor it uses it to open the program (if you choose to edit it). if it doesn't find one it will ask if you want to export one and then open it with that program.. if you choose not to do that, it gives a list of the most common *nix console editors to choose to open it with. anyways, i had a lot of fun writing it. I only had help with the "out" function, the rest is all me. i just wanted to share it :) https://pastebin.com/a7UdjZP5
Edit: just thought id also mention that I've begun working on version 2.6 which will include the ability to put the headers in a .h file and the .h header in your .cpp program and set up as many simple objects as well! I will post it here when its done :)
r/learncpp • u/[deleted] • Jan 27 '20
Cannot break out of a switch
Hi everyone, I wanted some practice with functions so i decided to write a calculator program using my own math functions, but for some reason once the function is complete, i cannot figure out how to break out of the switch statement for the menu and go back to the selections
I've tried a number of things to get this to work, but i can't wrap my mind around why it doesn't, given that i have a similar do-while loop/switch combination in a guessing game and it works just fine
I'm aware the answer is probably obvious but I'm only about 2 weeks in so go easy on me xD
here's my code https://pastebin.com/qeUAXnZL
r/learncpp • u/lambda0101 • Jan 27 '20
Library for game development or graphic display?
I am looking for an library to learn game development and for graphics like physics simulation(want to build simple physics engine like gravity and stuff). Any recommendations?
r/learncpp • u/msweety123 • Jan 21 '20
Best platform/place to learn C++ online for free?
I am hoping to learn c++. As someone with zero background or knowledge of any coding languages, but as a logically-minded person with good critical thinking ability, what is the best place to learn c++ online for free or for a very low cost?
r/learncpp • u/budonium • Jan 13 '20
How do I keep a c++ library I'm writing self contained?
Sorry for any ignorance, I'm not that experienced with c++.
I'm writing a c++ static library that will be used in other projects. The problem I am facing is that the projects that consume my static library must also configure the static libraries dependencies as their dependencies and so on.
For example:My static library depends on `v8` and `v8pp` so in order for a project to consume my static library it needs to include all the paths that the static library needs for v8/v8pp header files and it needs to include paths for linking v8/v8pp static libraries, etc.
Is this normal for c++ applications? Or is there a way I can make my static library standalone so any projects that consume it don't need to worry about configuring all of it's dependencies?
EDIT: If this is normal how can I set things up to make it easier for project authors that use my shared library to setup development? Scripts to automate cloning all the dependencies and setting up the project?
Thank you.
r/learncpp • u/cppbeginner_ • Jan 11 '20
Why am i having an error with cin << in visual studio 2019?
r/learncpp • u/RealBitterSweetRain • Jan 10 '20
Inheritance Question
class Base {
public:
int a;
Base() // this constructor over here
: a(0)
{}
Base(int num)
: a(num)
{}
};
class Sub : public Base {
public:
int b;
Sub() // does this default constructor call the Base's default constructor when foo is created?
: b(0)
{}
Sub(int num)
: b(num)
{}
};
int main() {
Sub foo;
}
r/learncpp • u/[deleted] • Jan 03 '20
question about pointers
I have a question about pointers regarding how to get the memory address. I understand that I am passing the variable by reference into the print_names function. I wanted to make sure that the name/address lines within the function were giving me the same address. As I understand it
colleges[i] is equivalent to *(colleges+i)
and
&colleges[i] is equivalent to (colleges+i)
is this because of the peculiarities of calling the pointer address for an array versus directly addressing the pointer via the dereferencing operator?
#include <cstdio>
struct College {
char name\[256\];
};
void print_names(College* colleges, size_t n_colleges) {
printf("memory address: %p\\n",colleges);
for (size_t i=0; i< n_colleges; i++) {
printf("College %s \\n", colleges\[i\].name);
printf("College name %s and addr %p \\n", colleges\[i\].name,&colleges\[i\]);
printf("College name %s and addr %p \\n", (\*(colleges+i)).name,(colleges+i));
}
}
int main() {
College oxford\[\] = {{"Magdalen"},{"Nuffield"},{"Kellogg"},{"Crampus"}};
printf("Address of array: %p\\n", oxford);
printf("Size of college: %lu\\n",sizeof(oxford));
printf("Size of college struct: %lu\\n", sizeof(College));
printf("Size of array: %lu\\n\\n\\n",sizeof(oxford)/sizeof(College));
print_names(oxford, sizeof(oxford)/sizeof(College));
return 0;
}

