/r/Cplusplus

Photograph via snooOG

C++ is a high-level, general-purpose programming language first released in 1985. Modern C++ has object-oriented, generic, and functional features, in addition to facilities for low-level memory manipulation.

Welcome to r/CPlusPlus

C++ is a high-level, general-purpose programming language first released in 1985. Modern C++ has object-oriented, generic, and functional features, in addition to facilities for low-level memory manipulation.

 

Rules:

Rule 1 - Don't Be A Nuisance

  • Treat others as you would like others to treat you.

  • Participate in good faith, be respectful, and do not insult others.

  • Remember, there is a person on the other side.

  • If you're being toxic or just here to cause trouble, you will be removed from the community.

 

Rule 2 - Content & Quality

  • This sub is for discussions around the C++ programming language. All posts must be in some way related to C++.

  • Comments on posts need to stay on topic and not attempt to threadjack.

  • No low-effort, spam, or advertisement/selling posts or comments.

  • No NSFW Content.

  • No misinformation.

  • Follow Reddiquette.

 

Rule 3 - Good Faith Help Requests & Homework

  • When posting a question or homework help request, you must explain your good faith efforts to resolve the problem or complete the assignment on your own. Low-effort questions will be removed.

  • Members of this subreddit are happy to help give you a nudge in the right direction. However, we will not do your homework for you, make apps for you, etc.

  • Homework help posts must be flaired with Homework.

 

Credits:

Upvote/Downvote Icons: u/Avereniect

Background: u/Robo-Guardian

/r/Cplusplus

42,629 Subscribers

4

SFML resources

I have to create a 3D game in c++ using SFML as a final semester Project. The complexity level of the game will be similar to the likes of snake game. kindly share some valuable sources to learn SFML.

3 Comments
2024/11/07
02:25 UTC

4

Casual talk about current C++ experiences

Is this a good place to talk about current C++ experiences? I'm working on a ~2k line project for work to keep my hand in programming. I switched out of programming 10 years ago after 20 years as a programmer to join the ranks of cybersecurity types, but still need to keep what chops as I can so that I can do code reviews.

All this to say, I'm looking for a place to talk about compilers, OS platform quirks for compiling C++, tools and the like without judgement.

3 Comments
2024/11/06
16:33 UTC

1

where i can go?

on long time, I have worked on windows system programming using c++ , but i need to move other domain, so what is the better domain to me, where i can go

6 Comments
2024/11/06
05:23 UTC

3

I can run a program using an overloaded operator with a specified return type without including a return statement. In any other function, not including a return statement prevents me from running the program. Why?

Essentially I was using the following: ostream& operator<<(ostream & out,MyClass myclass) { }

(Obviously I had stuff inside of it, this is just to highlight what was going wrong)

And I spent like half an hour trying to find out why I was getting out of bounds and trace trap errors. I eventually realized I completely overlooked the fact I didn’t put a return statement in the body.

If this were any other sort of function, I would’ve not been able to build the program. If I don’t include a return statement for a function returning a double I always get an error (I am using Xcode on Apple Silicon). Is there a reason for this?

10 Comments
2024/11/02
16:46 UTC

28

Total newbie to C++ trying to get my head around 2D arrays. Running this code outputs the contents of the board array once and then tells me I have a segmentation fault on line 18 and I have zero idea why. Any help would be greatly appreciated!

46 Comments
2024/11/01
21:03 UTC

0

Left Aligning the Info for the fetch script

I am making a Fetch script like Neofetch using C++ and wanted to left align the information. Although I am unable to achieve this.

structure of the project

```#include <iostream>

#include <string>

#include "fetch.h"

#include <algorithm>

#include <fstream>

#include <sys/utsname.h>

#include <unordered_map>

#include <ctime>

#include <iomanip>

#include <algorithm>

#include <vector>

#include <sstream>

using namespace std;

// Color codes

const string RESET = "\033[0m";

const string RED = "\033[31m";

const string GREEN = "\033[32m";

const string YELLOW = "\033[33m";

const string BLUE = "\033[34m";

const string MAGENTA = "\033[35m";

const string CYAN = "\033[36m";

const string WHITE = "\033[37m";

// Icons for system information

const string DISTRO_ICON = ""; // Distro icon

const string CPU_ICON = ""; // CPU icon

const string RAM_ICON = ""; // RAM icon

const string UPTIME_ICON = ""; // Uptime icon

const string KERNEL_ICON = ""; // Kernel icon

string fetchDogBreedArt(const string& breed) {

string filename = "../art/" + breed + ".txt";

ifstream artFile(filename.c_str());

string result, line;

if (artFile.is_open()) {

while (getline(artFile, line)) {

result += line + "\n";

}

artFile.close();

} else {

result = "Could not open file for breed: " + breed;

}

return result;

}

string fetchDistro() {

ifstream osFile("/etc/os-release");

string line, distro;

if (osFile.is_open()) {

while (getline(osFile, line)) {

if (line.find("PRETTY_NAME") != string::npos) {

distro = line.substr(line.find('=') + 2);

distro.erase(distro.find_last_of('"'));

break;

}

}

osFile.close();

} else {

distro = "Unable to read OS information";

}

return DISTRO_ICON + " " + distro;

}

string fetchCPUInfo() {

ifstream cpuFile("/proc/cpuinfo");

string line, cpuModel = "Unknown";

if (cpuFile.is_open()) {

while (getline(cpuFile, line)) {

if (line.find("model name") != string::npos) {

cpuModel = line.substr(line.find(':') + 2);

break;

}

}

cpuFile.close();

} else {

cpuModel = "Unable to read CPU information";

}

return CPU_ICON + " " + cpuModel;

}

string fetchMemoryInfo() {

ifstream memFile("/proc/meminfo");

long memTotalKB = 0, memAvailableKB = 0;

string line;

if (memFile.is_open()) {

while (getline(memFile, line)) {

if (line.find("MemTotal") != string::npos) {

memTotalKB = stol(line.substr(line.find(':') + 2));

} else if (line.find("MemAvailable") != string::npos) {

memAvailableKB = stol(line.substr(line.find(':') + 2));

break;

}

}

memFile.close();

}

double memTotalGB = memTotalKB / 1024.0 / 1024.0;

double memAvailGB = memAvailableKB / 1024.0 / 1024.0;

ostringstream oss;

oss << fixed << setprecision(2);

oss << RAM_ICON << " " << memAvailGB << " GB / " << memTotalGB << " GB";

return oss.str();

}

string fetchUptime() {

ifstream uptimeFile("/proc/uptime");

string result;

if (uptimeFile.is_open()) {

double uptimeSeconds;

uptimeFile >> uptimeSeconds;

uptimeFile.close();

int days = uptimeSeconds / 86400;

int hours = (uptimeSeconds / 3600) - (days * 24);

int minutes = (uptimeSeconds / 60) - (days * 1440) - (hours * 60);

ostringstream oss;

oss << UPTIME_ICON << " " << days << " days, " << hours << " hours, " << minutes << " minutes";

result = oss.str();

} else {

result = "Unable to read uptime information";

}

return result;

}

string fetchKernelVersion() {

struct utsname buffer;

string kernel;

if (uname(&buffer) == 0) {

kernel = string(buffer.release);

} else {

kernel = "Unable to read kernel information";

}

return KERNEL_ICON + " " + kernel;

}

vector<string> printSystemInfo() {

// Get the system information

vector<string> info = {

BLUE + fetchDistro() + RESET,

YELLOW + fetchCPUInfo() + RESET,

GREEN + fetchMemoryInfo() + RESET,

RED + fetchUptime() + RESET,

YELLOW + fetchKernelVersion() + RESET

};

// Find the maximum length of the information lines

size_t maxLength = 0;

for (const auto& line : info) {

size_t visibleLength = 0;

bool inEscapeSeq = false;

for (size_t i = 0; i < line.length(); i++) {

if (line[i] == '\033') inEscapeSeq = true;

else if (inEscapeSeq && line[i] == 'm') inEscapeSeq = false;

else if (!inEscapeSeq) visibleLength++;

}

maxLength = max(maxLength, visibleLength);

}

return info;

}

void printSystemInfoAligned(const vector<string>& artLines, const vector<string>& info) {

// Calculate the maximum width of ASCII art lines for consistent padding

size_t maxArtWidth = 0;

for (const auto& line : artLines) {

size_t visibleLength = 0;

bool inEscapeSeq = false;

for (size_t i = 0; i < line.length(); i++) {

if (line[i] == '\033') inEscapeSeq = true;

else if (inEscapeSeq && line[i] == 'm') inEscapeSeq = false;

else if (!inEscapeSeq) visibleLength++;

}

maxArtWidth = max(maxArtWidth, visibleLength);

}

// Calculate necessary padding width

const size_t paddingWidth = maxArtWidth + 4; // Add extra padding space

// Print ASCII art with system info aligned on the right

for (size_t i = 0; i < artLines.size() || i < info.size(); i++) {

if (i < artLines.size()) {

cout << setw(paddingWidth) << left << artLines[i]; // Print padded ASCII art line

} else {

cout << setw(paddingWidth) << " "; // Print empty space if no ASCII art line

}

if (i < info.size()) {

cout << "\t" << info[i]; // Print system info line with a tab space for alignment

}

cout << endl;

}

}

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

if (argc < 2) {

cout << "Please specify a dog breed as a command-line argument." << endl;

return 1;

}

string breed = argv[1];

// Get ASCII art and color it cyan

string asciiArt = CYAN + fetchDogBreedArt(breed) + RESET;

// Split ASCII art into lines

vector<string> artLines;

istringstream iss(asciiArt);

string line;

while (getline(iss, line)) {

artLines.push_back(line);

}

// Get system information

vector<string> info = printSystemInfo();

// Print aligned output

printSystemInfoAligned(artLines, info);

return 0;

}

```

this is the code

3 Comments
2024/11/01
09:31 UTC

1

25 years of haunting C++ circles with the specter of on-line code generation

I think it's more like Casper the Friendly Ghost, but I'll let you decide

https://www.reddit.com/r/codereview/comments/qo8yq3/c_programs

6 Comments
2024/10/31
04:21 UTC

7

does anyone have any resources that could help me review for my c++ midterm exam on the 31th?

I have my C++ mid-term in two days, and I’m reviewing everything I can, but I’m unsure if it's enough. Does anyone have any resources that could help me prepare more effectively? the topics i need to review are Branches, Loops, and Variables / Assignments i would really appreciate any help you guys could give me thank you.

5 Comments
2024/10/29
20:10 UTC

11

"Podcast interview: Rust and C++" By Herb Sutter on 2024-10-23

https://softwareengineeringdaily.com/2024/10/23/rust-vs-c-with-steve-klabnik-herb-sutter/

"In early September I had a very enjoyable technical chat with Steve Klabnik of Rust fame and interviewer Kevin Ball of Software Engineering Daily, and the podcast is now available."

"Disclaimer: Please just ignore the "vs" part of the "Rust vs C++" title. The rest of the page is a much more accurate description of a really fun discussion I'd be happy to do again anytime!"

"Here's the info..."

"Rust [and] C++ with Steve Klabnik and Herb Sutter"
https://herbsutter.com/
https://steveklabnik.com/

"In software engineering, C++ is often used in areas where low-level system access and high-performance are critical, such as operating systems, game engines, and embedded systems. Its long-standing presence and compatibility with legacy code make it a go-to language for maintaining and extending older projects. Rust, while newer, is gaining traction in roles that demand safety and concurrency, particularly in systems programming."

"We wanted to explore these two languages side-by-side, so we invited Herb Sutter and Steve Klabnik to join host Kevin Ball on the show. Herb works at Microsoft and chairs the ISO C++ standards committee. Steve works at Oxide Computer Company, is an alumnus of the Rust Core Team, and is the primary author of The Rust Programming Language book."
https://isocpp.org/
https://x.com/rustlang

"We hope you enjoy this deep dive into Rust and C++ on Software Engineering Daily."

"Kevin Ball or KBall, is the vice president of engineering at Mento and an independent coach for engineers and engineering leaders. He co-founded and served as CTO for two companies, founded the San Diego JavaScript meetup, and organizes the AI inaction discussion group through Latent Space."

"Please click here to see the transcript of this episode."
http://softwareengineeringdaily.com/wp-content/uploads/2024/10/SED1756-Rust-vs-Cpp.txt

Lynn

1 Comment
2024/10/29
01:27 UTC

4

General question: How do you create a project that uses more than one language?

I want to make a simple puzzle game using C++, but the UI part is an absolute pain. I’m using the Qt framework, and I keep running into problem after problem. I heard that using html is a lot easier, but I don’t know how to make a project that compiles more than 1 language. Can somebody help me? I’m using Visual Studio btw.

19 Comments
2024/10/28
20:52 UTC

7

Uninitialized locals

I was reading this thread and wondering about this

"We actually just did something similar already in draft C++26, which is to remove undefined behavior for uninitialized locals... that is no longer UB in C++26"

What is that about? Thanks in advance.

3 Comments
2024/10/28
00:12 UTC

0

Unsure if my University's teaching is any good

I'm in my first year of CS and in these first two months of classes, I'm pretty convinced the way they teach and the practices they want us to have are not the best, which is weir considering that it's regarded as the best one for this course in the country. I already had very small experience with C# that I learnt from YouTube for Unity game development, so my criteria comes from this little knowledge I have.

First of all, out of every example of code they use to explain, all the variables are always named with a single letter, even if there are multiple ones. I'm the classes that we actually get to code, the teacher told me that I should use 'and' and 'or' instead of && and ||. As far as I know, it's good practice to have the first letter of functions to be uppercase and lowercase for variables, wich was never mentioned to us. Also, when I was reading the upcoming exam's guidelines, I found out that we're completely prohibited of using the break statement, which result on automatically failing it.

So what do you guys think, do I have any valid point or am I just talking nonsense?

11 Comments
2024/10/27
23:09 UTC

1

How to stop commas in the middle of the string to be considered as a new column when exporting to .csv file?

https://preview.redd.it/kkntgyycr3xd1.png?width=2890&format=png&auto=webp&s=15855aaa7342b0a1609de41fa0e66c1ed8e48029

For example, I am trying to make a string called dataStream that appends together data and adds everything into a single column in the .csv file. However, everytime i try, the commas in the middle of the string cause the compiler to think that it is a new column and the resultiing .csv file has multiple columns that I don't want

10 Comments
2024/10/26
13:28 UTC

2

Online C++ Compiler

Looking for an Online C++ compiler to use in my Programming class. Our instructor usually has us use OnlineGBD, but It has ads, and it's cluttered and it looks old. Is there any alternative that has a modern UI, or some sort of customizability?

12 Comments
2024/10/26
02:43 UTC

12

best lightweight IDE for a student starting out?

So I need to download an IDE to do homework (I just started out and the programs are really simple, so learning what while, for and other functions). What would be a simple, "plug and play" IDE to start out?

67 Comments
2024/10/23
16:55 UTC

3

Function definitions in header or cpp file

What is the right policy to have on this? Should every function definition be in the header file, except when its not possible because of cross-include issues, or should everything go into the cpp file, except if it's required to be in the header file. Like with templates. Think also of how convenient it is to just use auto for return type and let it be deduced, and you cant do that if the definition is in the cpp file. And inline functions in a header do create visual clutter, but then in an IDE it is a standard feature to use fold/collapse on function definitions, so the clutter is removed.

As bonus question: do you think being possible to do this in two ways is a problem with C++ or an actually a good thing? I don't know many languages aside from C/C++ so I'm wondering how this is done in other languages. Whether it creates or reduces clutter. Also, so far I did not write any non-trivial project using c++20 modules, but I keep hearing that with modules there will be no more header files. Is this true? Will modules remove the need for separate declaration/implementation files?

7 Comments
2024/10/23
07:24 UTC

4

Anyone have tips for creating a resume?

I've been coding and learning for 10+ years, just got a BA in Computer Science but have had no luck im finding a job in the industry. Looking for any help possible.

5 Comments
2024/10/23
02:39 UTC

4

Trouble overall

So I am in the process of a career change. I cannot work the trades anymore. I'm 35 and started school again. I am pursuing a computer science degree and starting with my associate. I am one year and have taken a python class which is my only programming class, until this semester. This semester I started C++ programming and I'm 6 weeks in and have 2 weeks left and feel like I'm totally lost. The book is beyond confusing and makes no sense to me. Am I stressing entirely too much over this course?

5 Comments
2024/10/22
20:42 UTC

0

Tutorial source needed for using the XCode IDE for debugging C++ projects

I'm a fairly experienced C++ dev on multiple platforms. In the past, I've mostly developed on various UNIXes and MS Windows. I recently got an m-series mac and started developing on it. Since I was working on mac, I decided to give XCode a try. It seems to be a decent editor, but I can't figure out how to debug on this platform. For the time being, I'm editing and compiling as I go, then going back to the terminal to debug at the command line with lldb. Better than no debugger, but not as nice as having your watch variables and debug line flags in your UI. Does anyone have a good resource (please no videos) for figuring out how to use this V16 UI for debugging?

4 Comments
2024/10/21
00:53 UTC

0

Program error Dev C++

I keep trying to run certain files (new files I've created) and they keep telling me 'File not sourced' when I try to run and compile.

When going through older programs, I make changes but when I compile and run they give me the results of what the older code would have been. How do I fix this??

EDIT: It tells me 'Permission denied' in the File notes, but... this is my program. I am a beginner at programming, what do I do?

5 Comments
2024/10/20
22:12 UTC

0

What's the good practice, scope resolution operator or class object to use class member variables?

I have a class A, Class B and Class C

Class A # no private members Class B: # no private members

Class C: public Class A, public Class B{ void performManeuver( A aObj, B bObj) { aObj.functionInClassA(); moveToThisPosition(A::publicVarClassA, A::publicVar2ClassA) //OR moveToThisPosition(aObj.publicVarClassA, aObj.publicVar2ClassA) }; };

void moveToThisPosition(int speed, int position) {

};

int main() { A aObject; B bObject; C cObject;

court << "Enter val"; cin>> bObject.publicVar; cObject.myFunc( aObject, bObject); };

-------------------—------------------—---------------—----- So there are a few questions here regarding access:

  1. If I'm inheriting from Class A and B in C, why do I need to use and object in the Class C definition or just use the Class A or B members without it. I know for calling functions I need to use an instance of the class that contains the member function I'll be using.

  2. If I do use objects to refer to Class A or B members in C, why can't I just use the scope resolution operator in my class C's cpp file with the function definition with header inlcuded files for A, B. Is there a downside to using scope resolution operator or the object instead?

Thank you.

6 Comments
2024/10/18
19:37 UTC

2

help with spans please

hello, i am required to write a function that fills up a 2D array with random numbers. the random numbers is not a problem, the problem is that i am forced to use spans but i have no clue how it works for 2D arrays. i had to do the same thing for a 1D array, and here is what i did:

void Array1D(int min, int max, span<const int> arr1D) {

for (int i : arr1D) {
i = RandomNumber(min, max);  

cout << i << ' ';  
}
}

i have no idea how to adapt this to a 2d array. in the question, it says that the number of columns can be set as a constant. i do not know how to use that information.

i would appreciate if someone could point me in the right direction. (please use namespace std if possible if you will post some code examples, as i am very unfamiliar with codes that do not use this feature). thank you very much

17 Comments
2024/10/17
23:54 UTC

3

Exciting Updates: Template Addition and Enhanced MakeBuild Menu for Visual Studio Projects

Hey everyone,

I am excited to announce some significant updates to my GitHub repository. I've included a new template in the source code and updated the MakeBuild menu to generate the .vcxproj file and reopen it seamlessly in Visual Studio.

any suggestion/ feedback is appreciated

Check it out: MakefileBuildExtension

0 Comments
2024/10/17
15:03 UTC

6

How to Save Current Data When the User Exits By Killing the Window

Hay everybody, I am building a small banking app and I want to save the logout time, but the user could simply exit by killing the window it is a practice app I am working with the terminal here The first thing I thought about is distractor's I have tried this:

#include <iostream>

#include <fstream>

class test
{
public:
~test()
{
std::fstream destructorFile;
destructorFile.open( "destructorFile.txt",std::ios::app );

if (destructorFile.is_open())
{ destructorFile<<"Helow File i am the destructor."<<"\n"; }
destructorFile.close();
}
};

int main()
{

test t;

system("pause > 0"); // Here i kill the window for the test
return 0; // it is the hole point
}

And it sort of worked in that test but it is not consistent, sometimes it creates the destructorFile.txt file sometimes it does not , and in the project it did not work I read about it a bit, and it really should not work :-|

The article I read says that as we kill the window the app can do nothing any more.

I need a way to catch the killing time and save it . I prefer a build it you selfe solution if you have thanx all.

11 Comments
2024/10/17
11:23 UTC

3

New Makefile Template for GCC in Visual Studio IDE 2022 Now Available"? Keeps it direct and professional

Hey everyone,

I've updated my GitHub repository to include a Makefile template for creating and building projects using GCC in Visual Studio IDE 2022. Please ensure that 'make' and 'gcc' are added to your environment variables, as the build won't work otherwise.

Feel free to provide feedback and contribute at: Github.

Thank you!

2 Comments
2024/10/16
15:26 UTC

1

Unresolved External Symbol, Discord RPC

Hello! I am pretty new to C++, but I come from quite a bit of C# background.

For context, this is an extension to Metal Gear Rising (2012) to add RPC features

I've tried linking several versions of the Discord RPC Library (Downloaded from their official Discord.Dev site) but have been unable to get any to compile without an Unresolved Symbol Error for every external function, any ideas?

https://preview.redd.it/4sj7wr1e21vd1.png?width=1359&format=png&auto=webp&s=9fa1c8c6392d8b2a21a45260b4cf305d6d2f6c98

3 Comments
2024/10/16
02:16 UTC

3

my case 2 has error?

Hey everyone hope your days better than mine so far

So I wanted to practice my c++ after doing a lot of c and python and did a basic area and volume for 2 shapes and asked for user input but im getting 2 errors any help?

Edit image:

https://preview.redd.it/lqm95nxzhzud1.png?width=1297&format=png&auto=webp&s=fc876b2d29b0d73e799d67c327646665371f3eed

// code for finding the area and volume for cube, sphere using constructors
#include <iostream>
#define pi 3.14
class cube
{
    private:
    int lenght;

    public:
    cube (int a) :  lenght(a){} //square
     
       int area ()
       {
          return  (lenght * lenght)*6;
       }
       int volume ()
       {
        return (lenght*lenght*lenght);
       }
};

class sphere
{
    private:
    float radius;

    public:
    sphere (float a) :  radius(a){} //sphere
     
       float area ()
       {
          return  (4*pi*(radius*radius));
       }
       float volume ()
       {
        return ((4/3)*pi*(radius*radius));
       }

};
int main ()
{
int pick;
float l,r;

std::cout<<" Enter 1 for cube, 2 for sphere"<<std::endl;
std::cin>>pick;

switch(pick)
{
      case 1:
            std::cout<<"Enter the lenght of the cube "<<std::endl;
            std::cin>>l;
            cube sq(l);
            std::cout<<" The area of the cude is "<<sq.area()<<std::endl;
            std::cout<<" The volume of the cude is "<<sq.volume()<<std::endl;
            break;
      case 2:
           std::cout<<" Enter the radius of the sphere "<<std::endl;
           std::cin>>r;
           sphere sp(r);
           std::cout<<" The area of the sphere is "<<sp.area()<<std::endl;
           std::cout<<" The volume of the sphere is "<<sp.volume()<<std::endl;
           break;

}
return 0;

}
6 Comments
2024/10/15
20:45 UTC

3

Check Out My New Visual Studio Extension for Building Makefiles!

0 Comments
2024/10/15
14:06 UTC

Back To Top