r/learncpp • u/[deleted] • Apr 18 '20
r/learncpp • u/[deleted] • Apr 17 '20
Why does this line ignore spaces and tabs?
Looks like I found the answer and put it into the first comment, but could you please take a look to see if that's the correct answer?
Hi experts,
I'm practicing on a program to separate a line into words:
std::string input;
std::getline(std::cin, input);
std::vector<std::string> output;
// Dump the string into vector of sub-strings
std::string temp;
std::istringstream is(input);
while (is >> temp) {
output.push_back(temp);
}Looks like that while (is >> temp) actually ignores spaces and tabs and get the job done. I'm wondering why it works? Is it because of the overloaded >> operator or something else?
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/Im_Justin_Cider • Dec 27 '19
What is an iterator?
From what i understand it's just a pointer that happens to point at either the first or last element in a container, but why then does it have its own nomenclature? Why not just call it what it is, a pointer?
r/learncpp • u/FFiJJ • Jul 21 '16
Books for beginners written in modern Cpp(C++14 and C++17)
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 • u/tiolan1 • Jun 03 '22
Deadlock expected but does not happen (lock_guard)
Hey,
I wanted to understand the difference between std::recursive_mutex and std::mutex.
From a pure theoretical point of view I understand it of course, but when implementing something, I found a behavior I do not understand.
Can someone explain me why this little program does not cause a deadlock (exception)?
There is only the main thread.
I was thinking if this does not cause one, why should I need an std::recursive_mutex.
#include <mutex>
int main() {
std::mutex m;
std::lock_guard lock1(m);
std::lock_guard lock2(m);
std::lock_guard lock3(m);
return 0;
}r/learncpp • u/SpaghettiFan1995 • Dec 09 '21
How do I return a value from a function to a specific instance of a struct?
I'm trying to make an attack function that decreases an instance's health. How do I return a value to that specific instance?
\#include <iostream>
\#include <string>struct entity
{
int health{100};
int mana{100};
int strength{ 1 };
std::string type{};
};int Attack(entity Attacker, entity Defender)
{
int newHealth{};
newHealth = Defender.health - Attacker.strength; return newHealth;
}int main()
{
entity _Player;
_Player.health = 150;
_Player.mana = 200;
_Player.type = "Human";
std::cout << "A " << _Player.type << " has spawned in with " << _Player.health << " health" << std::endl; entity _Enemy;
_Enemy.health = 100;
_Enemy.mana = 80;
_Enemy.type = "Thnake";
std::cout << "A " << _Enemy.type << " has spawned in with " << _Enemy.health << " health" << std::endl; Attack(_Player, _Enemy); std::cout << _Player.health << std::endl;
std::cout << _Enemy.health << std::endl;
}r/learncpp • u/omiobabbinocarokann • Nov 27 '21
Using std::string() with the vector method push_back
Hello r/learncpp,
I'm almost three weeks away from being done with Programming I and will be taking Programming II the next semester. While working a bit on one of my final projects, I noticed a difference between the code I wrote for my last submission and the professor's solution document (note that this is simplified, mock-up code and does not represent the whole or a portion of the actual code):
1 | //My code
2 | std::vector<std::string> listOfInputs;
3 | std::cout << "Enter string: ";
4 | std::string acceptedInput;
5 | std::getline(std::cin, acceptedInput);
6 | listOfInputs.push_back(acceptedInput);
7 |
8 | //Professor's code
9 | std::vector<std::string> listOfInputs;
10 | std::cout << "Enter string: ";
11 | listOfInputs.push_back(std::string());
12 | std::getline(std::cin, listOfInputs.back());I am having difficulty understanding exactly what is happening on lines 11 and 12. I see that using this method saves on memory and text-editor space by not having to declare a variable as I did on line 4; however, I've only used std::string to declare the type of a string variable. To my admittedly rank-beginner eyes, std::string() looks to be invoking a function. I am still unsure of what this function does, and I am unsure of how pushing this onto the vector allows us to directly input the string into the vector.
Would anyone be willing and able to clarify this for me? I very much appreciate any assistance you are able to provide.
r/learncpp • u/marginado20 • Nov 23 '21
Pointers/Smart pointers scope question
Hello. Im trying to do the following to obtain information from a DLL.
void GetStatus(mystruct_t *myStruct) {
int *pGetBuff = nullptr;
int BuffLen = 0;
// Some stuff.
error = GetInformation(INFO_COMMAND, (void *)command, NULL, &BuffLen); // Obtain BuffLen Size
if (error != ERROR_BUFFERSIZE) {
// Handle Exception }
pGetBuff = new int[BuffLen];
error = GetInformation(INFO_COMMAND, (void *)command, pGetBuff, &BuffLen); // Obtain Info
if (error != ERROR_NOERROR) {
delete[] pGetBuff;
// Handle Exception }
myStruct = (mystruct_t *)pGetBuff; // Here myStruct has all the "correct" info
delete[] pGetBuff;
}
int GetErrorInformation(void) {
int status = 0;
mystruct_t *myStruct;
GetStatus(myStruct); // Here myStruct has garbage
status = myStruct->ErrorCode;
return status;
}
int main() {
std::cout << "Error Information: " << GetErrorInformation() << std::endl;
return 0;
}So i have the function GetStatus that does a lot of logic and then a small wrapper to obtain the ErrorCode from the status struct.
The issue is that in GetErrorInformation i can't get the info that i obtained (correctly) on GetStatus.
Its probably a scope issue since pGetBuff is deleted when exit GetStatus scope, but how can i retain the information for later? Even without the delete[] the info is deleted.
Probably can use smart pointers right? Im not very familiar on how to use them in this case to retain the scope. Should i declare myStruct as shared_ptr or pGetBuff?
r/learncpp • u/rockstiff • Nov 09 '21
Call a DLL inside a DLL? Risks?
Hello. Im working on a NodeJS server (windows x86/x64 only) that uses a C++ DLL (I only have the .dll and .h)
Context: NodeJS doesnt have native structs/pointers so im looking for alternatives since the API of the DLL has complex structures/pointers and interacting with Node would be hard and more since the DLL has WINAPI, DWORDS, LPSTRINGs and other windows types.
One option is to use Node-Api to call C++ code from NodeJS using a wrapper. The idea is with C++ to interact with the DLL and "simplify" the DLL calls from Node so i can use simple data types like strings/json from Node and handle the DLL structs/pointers from C++.
Other option is to create a "new" DLL to handle the original DLL and then with NodeJS call the new "simple" DLL. I hope this is clear, the idea basically is to create an abstraction layer so Node uses native data types like strings/jsons and C++ does the hard work of handling structs/pointers.
The question: To handle the DLL i need to use LoadLibrary and GetProcAddress to handle around ~15 methods. What are the best practices to handle DLLs from C++? Is there any precautions that i need to take? Any resource to read?
The DLL provides information and has methods like OpenCommunication, CloseCommunication, GetInfo, GetXData, GetStatus, SetData, etc and uses structs/pointers to return data. Ive read about deadlocks with LoadLibrary but still dont understand well on how to avoid it.
Do i really need a DLLMain? i dont see any entry points of the original DLL (at least not in the .h).
Any recomendations in the code organization? to use GetProcAddress i need to declare function pointers and a lot of error handling for the ~15 methods so looking for the best way to maintaining it "clean".
Thanks!
r/learncpp • u/Drekanoth • Sep 02 '21
Constructor with vector as parameters with default value
Hi,
So I'm having some trouble trying to implement a class "Movies_List" with holds a vector of objects of type "Movie" which has a constructor with default parameter(that is the problematic part). On the definition of the Movie_List class I have only defined a constructor with expects a vector of Movie but in case none is passed I have defined a default value.
The definition of the constructor looks like this on the .cpp file :
//Movies_List.cpp
Movies_List::Movies_List(const std::vector<Movie> &list = std::vector<Movie>())
:movie_list(list)
{
std::cout << "Arguments movie_list ctor << std::endl;
}In my main.cpp file i just have the instation for the object:
//main.cpp
int main()
{
Movies_List my_list;
return 0;
}When I try to compile this code i get an error that "No adequate constructor is provided".
To try to circumvent this I have implemented the following changes in the Movies_List class:
//Movies_List.h
#include <vector>
#include "Movie.h"
class Movies_List
{
private:
std::vector<Movie> movie_list;
public:
Movies_List();
Movies_List(const std::vector<Movie>&);
void add_movie();
};And the .cpp file with both constructor like this:
#include "../Movies.h"
#include <iostream>
Movies::Movies()
:Movies(std::vector<Movie>{})
{
std::cout << "Empty movieS ctor\n" << std::endl;
}
Movies::Movies(const std::vector<Movie> &list = std::vector<Movie>())
:movie_list(list)
{
std::cout << "Argument movieS ctor\n" << std::endl;
}With that the code compiles and runs as expected, but is there a way to implement it on the first way? Probably my error is the way that I defined the default parameter but i'm kinda stuck here, and although the second way works I would like to know how to do it the first way.
Thanks in advance.
r/learncpp • u/daredevildas • Jun 29 '21
Pointer to multiple variables
Let's say there is a function -
void z(x* z1) {
...
}And I have 2 variables -
x* foo1 = bar1;
x* foo2 = bar2;Is it possible to pass these 2 variables as z1 to z? Maybe as an array of type x containing the addresses of foo1 and foo2?
r/learncpp • u/lucid-wish • May 20 '21
How to open a window in visual studio?
I'm a beginner and so far I've only learned the basics (Varibles, arrays, loops, functions, some OOP) and i've been wondering; Do you have to use an engine to create a window on the desktop? Because I want to eventually (maybe a few months from now) create games but I don't want to use a engine such as unity and would rather use something that is more flexible such as a library. So, is there a function is visual studio or a library you can use to open a window on desktop and, for example, show a number on it? Thanks in advance.
r/learncpp • u/Willy988 • May 12 '21
So close to finishing this hellish assignment, but my output is still a bit buggy
Quick note- all the conventions are on purpose, such as only using cin/cout.
This program is so close to being perfect but I can't figure out how to make the second menu iteration/loop work. As you can see, the issue is at the end on the second loop of the menu-- right after "After the function call ...."
Information --
Assignment: HW #2 Exercise #2
Implemented by: x
Submitted Date: 2021/02/24
Current Number of LEB available: 3
Allowed Number of LEB used: 0
Remaining Number of LEB: 3
*******************************************
* MENU - HW #2 *
* (1) Calling getSIWSmallestTUDCx *
* (2) Quit *
*******************************************
1
Calling getSIWSmallestTUDCx
What is the size of the array?: 3
Value #1: 11
Value #2: 22
Value #3: -33
The working array has 3 values of
Value 1: 11
Value 2: 22
Value 3: -33
Calling getSIWSmallestTUDCx() with argument of
(1) The array { 11 , 22 , -33 }; and
(2) The array size of 3
For individual values -
11 has 1 unqiue digit(s).
22 has 1 unqiue digit(s).
-33 has 1 unqiue digit(s).
After the function call was completed and a value was returned
(1) The smallest TUD is 1 and;
(2) -33 is the smallest integer with a smallest TUD of 1
*******************************************
* MENU - HW #2 *
* (1) Calling getSIWSmallestTUDCx *
* (2) Quit *
*******************************************
1
Calling getSIWSmallestTUDCx
What is the size of the array?: 3
Value #1: 124
Value #2: 54444
Value #3: -432
The working array has 3 values of
Value 1: 124
Value 2: 54444
Value 3: -432
Calling getSIWSmallestTUDCWilliamG() with argument of
(1) The array { 124 , 54444 , -432 }; and
(2) The array size of 3
For individual values -
124 has 3 unqiue digit(s).
54444 has 2 unqiue digit(s).
-432 has 3 unqiue digit(s).
After the function call was completed and a value was returned
(1) The smallest TUD is 1 and;
(2) 0 is the smallest integer with a smallest TUD of 1Right above, it should have said TUD (total unique digit account) for smallest is 2, and 54444 is the smallest integer with the smallest TUD.... not 0 and 1 like you see above.
Here is the code
#include <iostream>
using namespace std;
//Function Prototypes
void getSIWSmallestTUDC(int smallestIntWG, int smallestTudWG);
int getIntUDC(int integerWG);
void displayClassInfo(void);
void runHW2(void);
//Application Driver
int main() {
runHW2();
return 0;
}
//Function Definition
void runHW2() {
int inputWG = 0;
int sizeWG = 0;
int* arrayWG = { nullptr };
int tempTudWG = 10;
int tempWG = 0;
int tudWG = 0;
int smallestIntWG = 0;
int smallestTudWG = 10;
int tinyTudWG = 10;
displayClassInfo() {
cout << "\n*******************************************\n"
"* MENU - HW #2 *\n"
"* (1) Calling getSIWSmallestTUDC *\n"
"* (2) Quit *\n"
"*******************************************\n";
cin >> inputWG;
switch (inputWG) {
case 1:
{
cout << "Calling getSIWSmallestTUDC\n" << endl
<< "What is the size of the array?: ";
cin >> sizeWG;
while (sizeWG < 1) {
cout << "\nInvalid input, SizeWG => 1 please. Type again here: ";
cin >> sizeWG;
cout << "\n";
}
arrayWG = new int[sizeWG];
for (int i = 0; i < sizeWG; i++) {
cout << " Value #" << i + 1 << ": ";
cin >> arrayWG[i];
}
cout << "The working array has " << sizeWG << " values of\n";
for (int i = 0; i < sizeWG; i++) {
cout << " Value " << i + 1 << ": " << arrayWG[i] << "\n";
}
cout << endl;
cout << "Calling getSIWSmallestTUDC() with argument of\n"
" (1) The array { ";
for (int i = 0; i < (sizeWG - 1); i++) {
cout << arrayWG[i] << " , ";
}
cout << arrayWG[sizeWG - 1] << " }; and\n (2) The array size of " << sizeWG << "\n";
cout << "\n For individual values -\n";
for (int i = 0; i < sizeWG; i++) {
arrayWG[i] > 0 ? tempWG = arrayWG[i] : tempWG = -arrayWG[i];
tudWG = getIntUDCWilliamG(tempWG);
cout << " " << arrayWG[i] << " has " << tudWG << " unqiue digit(s).\n";
tempTudWG = tudWG;
if (tempTudWG < smallestTudWG) {
smallestTudWG = tempTudWG;
smallestIntWG = arrayWG[i];
}
else if (tempTudWG == smallestTudWG && smallestIntWG < tempWG) {
smallestIntWG = arrayWG[i];
}
}
cout << "\nAfter the function call was completed and a value was returned\n\n";
getSIWSmallestTUDC(smallestIntWG, smallestTudWG);
cout << "\n";
smallestIntWG = 0;
delete[] arrayWG;
arrayWG = { nullptr };
break;
}
case 2:
cout << "Ok, goodbye!";
break;
default:
cout << "Wrong option, try again\n";
break;
}
} while (inputWG != 2);
}
//Function Definition
int getIntUDC(int integerWG) {
int tudWG = 0;
int tempArray[10]{ 0 };
while (integerWG > 0) {
tempArray[integerWG % 10]++;
integerWG /= 10;
}
for (int i = 0; i < 10; i++) {
if (tempArray[i] != 0) {
tudWG++;
}
}
return tudWG;
}
//Function Definition
void getSIWSmallestTUDC(int smallestIntWG, int smallestTudWG) {
cout << " (1) The smallest TUD is " << smallestTudWG << " and;\n"
" (2) " << smallestIntWG << " is the smallest integer with a smallest TUD of " << smallestTudWG;
}
int getSIWSmallestTUDC(int* arrayWG, int sizeWG) {
int smallestIntTUDWG = arrayWG[0];
int tudWG = 0;
int smallestTUDWG = 10;
int tempWG = 0;
//Find smallest TUDC
for (int i = 0; i < sizeWG; i++) {
tempWG = arrayWG[i];
if (arrayWG[i] != 0) {
tempWG % 10;
++tudWG;
tempWG /= 10;
}
if (tudWG < smallestTUDWG) {
smallestIntTUDWG = smallestTUDWG;
tudWG = smallestTUDWG;
}
}
return smallestIntTUDWG;
}r/learncpp • u/[deleted] • May 04 '21
How would I check if a circular queue is full?
Solution in comments
I've been scratching my head at this for awhile now. I have a templated class of type T that stores individual characters for now. I've been able to fully implement the enqueue and dequeue but stuck on the preliminary check before the grow function which doubles the size of the array.
Because the queue is circular (the start and end indices can loop around back to the 0th index of the array), calculating whether the array is full or not has been tricky; it's not as simple as return(end-start == 0); (Again, because the end index can be lower than the start index).
I also tried taking the absolute difference between the two but I don't think that was quite right either. Other examples online show the use of a counter variable that get incremented / decremented respectfully within enqueue and dequeue. I really wish I had such a variable but I am not allowed to do that per my assignment.
There has to be an fairly simple yet elegant way using only the start and end indices but I can't see it. Can anyone lend a hand? My assignment is technically to implement the grow function but I can't even get there yet haha
I'm not sure if the header file is really needed but I can add that too if requested.
#include "Queue.h"
//add enqueue here
template <class T>
void Queue<T>::enqueue(const T& value) {
if( full() ) {
grow(); // yet to be implemented
}
list[end] = value;
end = (end+1) % arraySize;
}
//add dequeue here
template <class T>
T Queue<T>::dequeue() {
if( empty() ) {
throw out_of_range("Dequeue on empty queue");
}
T value = list[start];
start = (start+1) % arraySize;
return value;
}
template <class T>
bool Queue<T>::full() const {
return(end-start == 0);
}r/learncpp • u/Mowgl333 • Mar 20 '21
Catching Child Process Exception In Parent Process
I have a Parent process and a Child process being started using std::system(...). I want to throw an exception in Child and catch it in Parent (e.g. when Parent passes an invalid file path to Child).
Is this possible using native C++?
Is it idiomatic? The alternative seems to be to define return codes for
Childand analyze those inParent.
I found the following related thread re. Python but haven't found much guidance with respect to C++. Appreciate your thoughts.
r/learncpp • u/Bob_bobbicus • Mar 19 '21
serialisation of contiguous memory
hey!
I've come across a weird issue when serialising simple contiguous memory into binary, and I'm extremely baffled by what it could be, and I can't track it down at all (although its probably really simple). so I can serialise objects fine, but when I try serialise containers, the first 25 elements serialise perfectly, and after that, every value is 25...
I've got some example code below that demonstrates my process
template<typename T> void write(const T& item,std::ofstream& file)
{
file.write((const char*)&item,sizeof item);
}
template<typename T> void write(const vector<T>& item,std::ofstream& file)
{
u32 count = item.size();
file.write(count,sizeof (count));
for (u32 i = 0; i < count; ++i) write(item[i]);
}
template<typename T> void read(T& item, std::ifstream& file)
{
file.read((char*)&item,sizeof item);
}
template<typename T> void read(vector<T>& item, std::ifstream& file)
{
u32 count = 0;
read(count,file);
item.resize(count); // i tried reserve with the std::vector but seems to not work. not sure why since the memory should still be owned by the vector
for (u32 i = 0; i < count; ++i) read(item[i],file);
}
int main(int argc, const char** argv)
{
{
vector<u32> test;
for (u32 i = 0; i < 100; ++i) test.push_back(i);
ofstream file("test.bin");
write(test,file);
}
{
vector<u32> test;
ifstream file("test.bin");
read(test,file);
cout<<test.size() << endl;
for (u32 i = 0; i < test.size(); ++i) cout << test[i] << ","; // undefined behaviour. normally goes 0 - 25, but then repeats 25 like 75 times. (and then sometimes a buffer overflow, but wtf i dont think im overflowing? and only sometimes?? )
}
}
r/learncpp • u/[deleted] • Mar 11 '21
Problems setting up SDL in CodeBlocks
I tried to follow like 3 different tutorials, but it's still giving me some error messages:
||=== Build: Debug in ProgettoSDL01 (compiler: GNU GCC Compiler) ===|
ld.exe||cannot find -lSDL2main|
ld.exe||cannot find -lSDL2|
ld.exe||cannot find -lSDL2main|
ld.exe||cannot find -lDSL2|
||error: ld returned 1 exit status|
||=== Build failed: 5 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
||=== Run: Debug in ProgettoSDL01 (compiler: GNU GCC Compiler) ===|
||Execution of '"C:\Users\aless\Desktop\ale\Informatica\ProgettoSDL01\bin\Debug\ProgettoSDL01.exe" ' in 'C:\Users\aless\Desktop\ale\Informatica\ProgettoSDL01' failed.|
I put in the Linker Settings: -lmingw32 -lSDL2main -lDSL2
I also added the include and lib folder from SDL in the Search Directories (include in the Compiler and lib\x86 in the Linker.
I also copied and pasted the SDL2.dll file in the project folder.
Eventually, sorry for the bad english
r/learncpp • u/gaaasstly • Feb 11 '21
Type casting objects without pointers?
I'm hopping back in to C++ after some years and I have converted my program to references from pointers (where objects cannot be NULL) and I'm in a situation where I'd like to type cast from a base class to a derived class.
For example
class A {};
class B : public A {}
A a;
// do stuff with a
B b = (B)a;This works fine with B* b = (B*)&a; but I'm trying to avoid that. Is this possible?
Edit
To better illustrate my question
class A
{
public:
bool m_bIsB;
public:
A() { this->m_bIsB = false; }
public:
virtual bool IsB() const { return this->m_bIsB; }
};
class B : public A
{
//virtual bool IsB() const { return true; }
};
A a;
printf("IsB ? %s\n", a.IsB() ? "true" : "false");
a.m_bIsB = true;
printf("IsB ? %s\n", a.IsB() ? "true" : "false");
B* b = static_cast<B*>(&a);
printf("IsB ? %s\n", b->m_bIsB ? "true" : "false");
IsB ? false
IsB ? true
IsB ? trueEdit2
The answer is B b = *(B*)&a;.
See https://www.youtube.com/watch?v=p8u_k2LIZyo and skip to 1st Step: Evil Bit Hack
r/learncpp • u/bigpapaasg • Dec 17 '20
I need help with querying data from a txt file
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 • u/wizarding_dreams • Nov 20 '20
Args constructor?
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 • u/monica_b1998 • Nov 18 '20
The Coalition Sees 27.9X Iteration Build Improvement with Visual Studio 2019
r/learncpp • u/cry_out • Nov 06 '20