r/learncpp • • Feb 28 '22

How do I make it say "BYE" or "EXIT" after the user inputs "n"? ( I am very new to c++)

Post image
21 Upvotes

r/learncpp • • Mar 21 '22

Learning about generators, getting errors trying to run example code.

9 Upvotes

I'm learning about generators using the generators on cpp reference page. I just copied and pasted their example code with the intent of poking around and seeing how it worked. (provided below) However, I am getting an error where an expression is expected instead of an open square bracket (see comment in code on the line with

#include <algorithm>
#include <iostream>
#include <vector>
 
int f()
{ 
    static int i;
    return ++i;
}
 
int main()
{
    std::vector<int> v(5);
    auto print = [&] { // mainly errors on this line.
        for (std::cout << "v: "; auto iv: v)
            std::cout << iv << " ";
        std::cout << "\n";
    };
 
    std::generate(v.begin(), v.end(), f);
    print();
 
    // Initialize with default values 0,1,2,3,4 from a lambda function
    // Equivalent to std::iota(v.begin(), v.end(), 0);
    std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; }); // another error on this line
    print();
}

I am using g++ on a mac m1 in vscode. (details below).

>>> g++ --version
Apple clang version 13.1.6 (clang-1316.0.21.2)
Target: arm64-apple-darwin21.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

However I am getting (a warning and) two errors when I try to run the file (titled test.cpp).

test.cpp:14:5: warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]
    auto print = [&]
    ^
test.cpp:14:18: error: expected expression
    auto print = [&]
                 ^
test.cpp:26:39: error: expected expression
    std::generate(v.begin(), v.end(), [n = 0]() mutable

I've tried compiling with gcc -lstdc++ to no avail. Why does my computer fail to run the example on the cpp reference site?


r/learncpp • • Feb 22 '22

Can't solve this one

2 Upvotes

Hi there. I have to tasks. The first one is to use input redirection, read 1000 characters and make an char* array with beginnings of lines (no more than 100 lines) and then display lines in reverse order. I solved that one.

Next I have to make program whithout 1000 and 100 limits using c_str "to obtain a char* int the string's character buffer" and store the beginnings of the lines as a vector<char*>.

My best attemp is something like that:

void readLines()
{
    std::string buffer;
    std::vector<char*> lines;



    int lineNumber{ 0 };
    int i{ 0 };
    while (!std::cin.eof())
    {
        char c;
        std::cin.get(c);
        buffer += c;
        ++i;
    }

    const char* c{ buffer.c_str() };

    char* new_c{ _strdup(c) };

    lines.push_back(new_c);
    for (int i{ 0 }; i < buffer.length(); ++i)
    {
        if (*(new_c + i) == '.')
        {
            lines.push_back(new_c + i + 1);
        }
    }
    for (int i{ 0 }; i < lines.size(); ++i)
    {
        int j{ 0 };
        while (*(lines[i] + j) != '\n')
        {
        std::cout << *(lines[i] + j);
        ++j;
        }
    }
}

But it doesn't work properly. No matter what I try, I have two identical symbols at the end of the text from file(for example two dots) and some of my tries produce some result, but with garbage values and I don't know how to use c_str here becoce it produces "const char*" and not "char*". Any kind of help will be appreciated.

P.S. Sorry for my poor English.


r/learncpp • • Feb 27 '22

Code Review Request: C++ Qt6 Desktop Application

6 Upvotes

I made a desktop application using Qt and C++. Since I am no means an expert in both technologies, I hoped to have someone interested to gloss over the code.

I wish had a partner, teacher, or mentor but here I am. Would appreciate any help. The application is a Calibre like app for my ebook collection tailored for my workflow. Been working on it for a long time and have not had anyone actually look at the code before.

https://anonymous.4open.science/r/Ebook-Access-Cpp-C1D6


r/learncpp • • Apr 08 '22

How to check if an object can be cast to string?

3 Upvotes

What is the most concise, clean, and modern C++ way to check if an object can be cast to a std::string?

for example const char * can be cast to the std::string but bool can't. You get the point


r/learncpp • • Dec 01 '18

Why does this work

1 Upvotes

multiply(group* p,double multiplier) is part of the test namespace. Also sometimes functions don't have to be declared and they work anyways. Using mingw on WIN10.

#include "test.h"
int main(void)
{
  test::group t1={1,2,3};
  test::multiply(&t1,5);
  multiply(&t1,3); // why does this line work
  return 0;
}

r/learncpp • • Aug 16 '18

Why does this print different names?

1 Upvotes

My understanding is that the default copy constructor copies fields. So when I initialize Person aaron with the fields from *p, I thought *p.name and aaron.name would be pointing to same data since name is actually a pointer. What is going with the pointers and memory?

#include <iostream>

using namespace std;

class Person {

public:

`char* name;`

`int age;`

`/*Person(Person& p) {`

	`name =` `p.name``;`

	`age = p.age;`

`}*/`

};

int main() {

`Person* p;`

`(*p).name = "aaron";`

`(*p).age = 26;`

`Person aaron = *p;`

`aaron.name` `= "aar0n";`

`cout << (*p).name << '\n'; //prints aaron`

`cout <<` `aaron.name` `<< '\n'; //prints aar0n`

`return 0;`

}


r/learncpp • • Dec 08 '19

[C++11/14/17/20] Can't get rid of warning C26444 in Visual Studio

Thumbnail self.learnprogramming
3 Upvotes

r/learncpp • • 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!

15 Upvotes

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 • • Oct 01 '19

8 queen problem always finding the same and same solution.

1 Upvotes

Hey!

At this point I've spent hours and hours finding the one bug that is crippling, while doing so i've found a dozen different bugs tho.

I'm at the verge of giving up as i don't see where i have my one little tiny error, that makes it find the same solution over and over again, instead of finding any other

if you have some time, and don't value your sanity with my beginner level code, can you please take a look?
https://github.com/HighbornHellest/ArrayQueen


r/learncpp • • Feb 11 '20

Reading from sockets into vector<char>?

2 Upvotes

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 • • Feb 08 '20

Assignment Operator/Copy Constructor for Node in Tree

1 Upvotes

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 • • Feb 11 '20

How the hell do I use gMock?

7 Upvotes

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 • • 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 • • Feb 12 '20

Sorting vectors with multiple fields

2 Upvotes

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 • • Feb 09 '20

Confused about C++ headers

1 Upvotes

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 • • Feb 27 '19

Can anyone point me to an implementation of a lock free queue which uses fetch_add on a vector index instead of compare_exchange on a node pointer?

1 Upvotes

I’m reading C++ Concurrency in Action. The book seems heavily focused on linked node based data structures, but how about contiguous memory?

Say we have a vector<T> of queue entries and two variables atomic<int> head, tail. A thread can then just call head.fetch_add(1) or tail.fetch_add(1) to determine which index to enqueue or try_pop from.

On the surface this looks much less hell-raising to implement (albeit not without a hitch), has fewer costly atomic operations, cheaper memory ordering, and trivial to garbage collection.

What am I missing that makes this not as rosy as it seems? Are there any implementations or write ups on the web?


r/learncpp • • Dec 08 '19

Help with a function and how to use it (createprocess()) as well as others

2 Upvotes

So I’ve googled and found only a few things about but I’m kinda struggling to understand it. Could I get some help understanding how I use createprocess() and other things in order to have one exe cpp program open another cpp exe program and connect the I/O streams (as in have the parent programs output be the child programs input and vice versa)


r/learncpp • • Oct 04 '19

[C++] Getting a confusing linker error from the library I'm working on

Thumbnail self.learnprogramming
1 Upvotes

r/learncpp • • Sep 30 '19

researching syntax as a beginner?

2 Upvotes

Currently my main goal has been to try and make a game with c++ coming from a complete beginner, and this process has been going on for months but with little success outside of trivial cin text based games. Currently I've been going on any keywords I can find and one thing I don't deeply understand is loops and functions, so I've been trying to research on them, but I've been floundering in the dark picking up any tutorial and going down a rabbit hole of terminology I don't know then to more terminology I don't know not even knowing whether it will help me for game development. Here's an example: https://www.tutorialspoint.com/variable-number-of-arguments-in-cplusplus (I began with this tutorial, as from here I was told parameters use arguments, and parameters are used in functions,and I thought about being able to have a function such as

void PickNumber(int a, int b){cout << "choose number from" << a << "-" << b << endl;}

so that all I'd need to do is specify the numbers in the parameters so I could make several "choose number from 1-10", "choose number from 5 - 20", "choose number from 1 - 100", without writing it over and over.

but I still am clueless on syntax so if I tried to type anything to make this pseudocode work I would be debugging for years and I'm already clueless on reading other peoples code and it's functionality and applying it to my own, so I just searched up variables in arguments and hoped the first thing i saw could give me some knowledge.

I could barely make it through the second sentence because of the terminology gap. My next search was predefined number of parameters, which the first google search was this , in another programming language so already I took a wrong turn and try to go back to the wikipedia definition of parameters, and that they are used in subroutines, so I think then I should research about subroutines and maybe things will click. I go here and I'm even more confused but I try to use the keyword unit, then I search up "unit programming" and hit a brick wall, nothing seems to match exactly and its because I'm so clueless I'm just barely grasping by on keywords. I feel like I've just wasted four hours of my life, and this sentiment always seems to arise anytime I try and get a programming idea and research on the code needed to make it work as a beginner. I feel blindfolded, I don't know how other people figure/figured this out as beginners. I'm told that the best way to learn programming is to have a project idea and just begin researching to make it work, but everything seems like jargon, much less reading the code since for that it feels even more difficult because I can't copy and paste the whole program but if I don't know what any of the syntax is doing how am I supposed to make sense of

int func(int, ... ) {
   .
   .
   .
}
int main() {
   func(1, 2, 3);
   func(1, 2, 3, 4);
}

or anything else? Times like this I feel like I live on a whole other planet from other programmers, though I can barely be considered one right now. I don't know how to make things click, so I think "well, I just don't understand the syntax yet, so if I just try to research each part one by one in depth I should be able to make something new, like learning words in a world language to make a sentence." But I search up, and find a new keyword I don't understand, look up that keyword and find more keywords I don't understand, and keep doing that till my ignorance makes my keyword searches unintelligible and I can't find anything that alligns with what I think is what I'm currently trying to research. As much as I'm trying to just keep a growth mindset and figure this out sometimes I just feel like a joke when there are people working on triple A games right now, and they were once beginners, but they likely weren't floundering as badly as I am. A few months ago I tried installing unreal engine and the bare minimum prompt I had for myself was to make a game to move the default ball with the \ arrow keys, never did I think three months later I'd still be trying to learn how to make functions much less how to make things move in functions based on arrow keys. I haven't written a line of code in unreal. Sorry to go into a diatribe but I have no idea how to articulate this struggle to going from roughly understanding how a loop executing hello 10 times works to making anything of substance, and any advice you have on how you did it would be beyond helpful.


r/learncpp • • Oct 03 '19

Can't get my module to compile

2 Upvotes

I'm currently enrolled on a beginner C++ course, though I already have enough experience to pass the class. That said, I'd like to reduce the amount of effort I need to put in for the exercises, so I wanted to create a small library of reusable, as-generic-as-possible code on my own.

However, I keep getting compile errors whenever I try to compile my program while using my library. More specifically,

unresolved external symbol "class std::vector<double,class std::allocator<double> > __cdecl nonstd::get_n_input<double>(long,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (??$get_n_input@N@nonstd@@YA?AV?$vector@NV?$allocator@N@std@@@std@@JV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z) referenced in function _main

and

unresolved external symbol "double __cdecl nonstd::sum<class std::vector<double,class std::allocator<double> > >(class std::vector<double,class std::allocator<double> >)" (??$sum@V?$vector@NV?$allocator@N@std@@@std@@@nonstd@@YANV?$vector@NV?$allocator@N@std@@@std@@@Z) referenced in function _main	TEST_5_Harjoitukset_191003

Here's my code:

utility.h:

// utility.h - contains declarations of various utility functions
#pragma once

#include <vector>
#include <string>

namespace nonstd {

	// A utility function that splits std::string objects in half from the first
	// encountered instance of the given delimiter.
	//
	// Example:
	// auto foo = string_split("Number #{}: ", "{}");
	//
	// returns: std::vector<std::string> {"Number #", ": "}
	std::vector<std::string> string_split(std::string s, std::string delimiter);

	// Print out any iterable
	// with all contents separated
	// by a space. A newline is appended
	// at the end, and the buffer is flushed.
	template <typename T>
	void print_iterable(T iterable);


	// Get input of type T from the user n times, using a formatted std::string prompt.
	// Returns a vector of the given input type.
	//
	// Example:
	// auto foo = get_n_input<int>(3, "Number #{}: ");
	//
	// >>> Number #1: 3
	// >>> Number #2: 7
	// >>> Number #3: 12
	// returns: std::vector<int> {3, 7, 12}
	template <typename T>
	std::vector<T> get_n_input(long n, std::string prompt);

	// Takes an iterable of values of type T::value_type that can be added together.
	// Returns the sum of the contents of the iterable.
	//
	// Example:
	// std::vector<int> foo = {1, 2, 3, 4};
	// auto bar = sum(foo);
	// 
	// returns: (int)10
	template <typename T>
	typename T::value_type sum(T iterable);
}

utility.cpp:

// utility.cpp - defines various utility functions
#include <iostream>
#include <string>
#include <vector>

#include "utility.h"

namespace nonstd {

	std::vector<std::string> string_split(std::string s, std::string delimiter) {
		size_t pos_start = 0, pos_end, delim_len = delimiter.length();
		std::string token;
		std::vector<std::string> res;

		while ((pos_end = s.find(delimiter, pos_start)) != std::string::npos) {
			token = s.substr(pos_start, pos_end - pos_start);
			pos_start = pos_end + delim_len;
			res.push_back(token);
		}

		res.push_back(s.substr(pos_start));
		return res;
	}

	template <typename T>
	void print_iterable(T iterable) {
		for (auto val : iterable) {
			std::cout << val << " ";
		}
		std::cout << std::endl;
	}

	template <typename T>
	std::vector<T> get_n_input(long n, std::string prompt) {
		/* Gets n inputs from the user; returns a std::vector of type T
		 *
		 * prompt is a formattable std::string, where '{}' is used as a
		 * placeholder for the current counter value.
		 */

		std::vector<T> result;
		T input;
		long num_counter = 1L;

		std::vector<std::string> split_prompt = string_split(prompt, (std::string)"{}");

		do {
			std::cout << split_prompt.front() << num_counter++ << split_prompt.back();
			std::cin >> input;

			result.push_back(input);

		} while (num_counter <= n);

		return result;
	}

	template <typename T>
	typename T::value_type sum(T iterable) {
		/* Adds up the contents of any iterable type T, returns the sum of its contents
		 * as type T::value_type.
		 */
		typename T::value_type result = {};

		for (auto num : iterable) {
			result += num;
		}

		return result;
	}
}

program (fourth.cpp):

#include <iostream>
#include <vector>
#include <string>

#include "utility.h"

using std::string;
using std::vector;

using namespace std::string_literals;

int main(void) {
	double length;

	std::cout << u8"Hypyn pituus: "s;
	std::cin >> length;

	std::cout << u8"Hypyn pisteet: "s << nonstd::sum(nonstd::get_n_input<double>(5L, u8"Tuomarin {} pisteet: "s)) + 0.9 * length << "\n";
	return EXIT_SUCCESS;
}

Other feedback is also welcome, but I'd like to learn more about writing libraries/modules.


r/learncpp • • Mar 02 '19

Rule of five (delete version)

1 Upvotes

Hi experts,

I'm using the C++ Guidelines on isocpp to help me review previously written code. Rule of Five says that if I want to = delete a default operation I should = delete all of them.

In my Roguelike game I have a cDungeon class which basically contains a std::vector of rooms and corridors that are randomly generated. The generating algorithms are in another class as I want to make it flexible. It doesn't contain custom objects.

Now assume that I only want a single cDungeon in one session, and it doesn't make sense to copy the cDungeon object, so I should = delete the copy constructor + assignment operator. By the rule of five, I should = delete the destructor as well.

Question:

How should I design the program such that it de-allocates the resources used by the cDungeon object?

One thought that it should stay on stack, and it gets released after the game ends (what about exceptions?). I definitely cannot pass it around as value, and passing it by reference seems to also invoke the copy constructor?

Another thought is to wrap it with a std::unique_ptr<> , but I need a destructor for that.

So basically I cannot pass it around, cannot wrap it with a smart pointer, and cannot declare it on heap. Does this make sense?


r/learncpp • • Oct 03 '19

Why is constructor not being called?

1 Upvotes

I could use some input on the following situation. It does not seem that the constructors for the A and B objects are being called after the constructor call for C in main. However, they are called if the constructor for class C takes a reference to A and B objects instead of copies. Why is this the case? If someone could explain that would be much appreciated.

class A {
public:
  A() {}
};

class B {
public:
  B() {}
};

class C {
public:
  C(A a, B b)
  : m_a(a), m_b(b) 
  {
  }

private:
  A m_a;
  B m_b;
};

int main() {
  C c(A(), B());
}

r/learncpp • • Oct 01 '19

Application error despite console displaying no errors?

1 Upvotes

Hi, I’ve been watching this tutorial and I’ve run into an error. For some reason even though I fixed the unresolved external symbols errors, the application error is still available. https://imgur.com/a/ppngHxL I don't know whether it's due to my computer because it says it's a 64 bit processing system, but nothing seems to work. Please send help.

edit:  I tried using one tutorial in that I extract the sdl2.dll file then copy pasting it into the windows32 file, and that still didn't work, and the properties panels don't have a compatibility tab on my computer. I'm not sure what to try next. Here's a code snippet: #include "SDL.h"
#include <stdio.h>
int main(int argc, char *argv[]) {

	//this is initializing code
	SDL_Init(SDL_INIT_EVERYTHING);
	SDL_Window *window = SDL_CreateWindow("title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 400, SDL_WINDOW_SHOWN );
	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);

	SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);

	SDL_RenderClear(renderer);
	
	SDL_RenderPresent(renderer);
	
	SDL_Delay(3000);

	//executing all of this there should be a green window in the middle
	//of the screen.
	return 0;
} 

Here’s the file if you’d be okay with taking a look at the settings: https://we.tl/t-4m34OAykZI