/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.
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.
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
i am faling my first semester badly but i dont want to give up hope as finals are 40% of grade could anyone be willing to take some time out to tutor me and go over with me over cocnepts and all :(
Hey, I am a Freshman level CS student and were using C++. I have a problem with not being able to populate a struct array fully from a .txt file. I have it opening in main, calling the .cpp that uses the .h but something about my syntax isnt right. I have it operating to a point where it will grab most of the first line of the file but nothing else. I have been trying things for about 4 hours and unfortunately my tutor isnt around for the holiday. I have tried using iterating loops, getline, strcpy, everything I can think of. I need some help getting it to read so i can go on to the next part of my assignment, but I am firmly stuck and feel like Ive been beating my head against my keyboard for hours. ANY help would be greatly appreciated. I can post the .cpp's .h and .txt if anyone feels like helping me out. Thank you in advance.
https://pastebin.com/eHtAe6qN - MAIN CPP
https://pastebin.com/W632c8kp secondary cpp
So, I started a small side project to learn C++ and improve my understanding. I am creating a symmetric cipher with a key of 256! complexity with several rounds of encryption and mutation of the key.
I am trying to be as close to the standard C++ as possible, so there are no external libraries involved (not even for unit testing).
If you are interested in checking it out and giving me some feedback, the repo is available at: https://github.com/chronos-alfa/chronocipher
This morning I wasted about 25 minutes of my life debugging a bug I caused myself months ago.
When something broke, I reviewed the code I had just written and what I might have inadvertently changed in the process. When everything looked fine, I launched the debugger to review the new code, line by line. As everything appeared to work as expected, I slowly went up the class hierarchy, confirming every value was correct.
In the end, I realised one of the variables in the base class was uninitialised. It still worked as expected for months. Possibly, one of the later changes coincidentally changed the initial state of that memory space. That's what we call Undefined Behaviour (UB).
Mind you, I've been using C++ since 1995 🤦🏻
Im starting college in a couple weeks and I'm taking a program with a decent amount of programming.
My budget is 600$ to 700$ or a little over
My requirements that are provided by my school are 16gb of ram, atleast a half a tb of storage.
And preferably w8th upgradable ram and storage
Let’s say I have a class named Person, and in Person I have a member personName of type string. I also have a member function setPersonName.
Let’s say I have a class named Car, and in car I have a member driverOfCar of type Person. (driverOfCar is private, questions related to this further down).
In main, I declare an object myCar of type Car. Is there some way I can call setPersonName for the myCar object? The idea is that I want to name the driverOfCar.
The only way I could think of is if driverOfCar is a public member in Car. Is that something I should consider doing? Is there a better way to achieve utilizing the mutators and accessors of Person from Car? Eventually, I’ll have a ParkingLot class with Car objects. Should I just combine Person and Car?
Hi
I have some experience developing control applications on platforms like STM32, mainly has been motor control, some I/O manipulations and comm protocols I have an interview with a company that makes power transformers using power electronics, they emphasized alot on c/c++ so if anyone can give me some examples and guidance of control related applications development in c/c++ Thanks all
I want to learn about this topic because I want to expand my knowledge. I've been working as a backend developer, and I want to explore other, more complex areas of programming. I don't think I'll create the next Unity—that's not my goal. I simply want to learn and build something useful, like an aerodynamic simulator or something similar. Could you recommend any books, tutorials, videos, or other resources that would help me get started on this topic?
I would be incredibly thankful if someone with expertise in this area could provide me with a roadmap to guide me from zero to as close to expert level as possible
So, i basically just started college, and wanted to learn DSA and C++ for college.. I basically planned to watch this 6hr tutorial by Bro Code and then improve upon it by practicing more and more.. Is it a good approach or should i do something else... Any suggestions about resources or any book suggestions would be very helpful... I also know basic python.
You can do it in xcode, but I want to do it without xcode.
I don't know if they are static or dynamic, and I don't know the difference so ELI5.
The program I need to make is very simple, which is why I think even with my shockingly limited knowledge I can pull it off.
I'm learning c++ through learncpp.com and I know that all of these subjects are important but do I really need to go through each chapter right now? I just want to learn the basics of c++ like functions, data types, conditional statements, or stuff like that, and how to use it. Then use what I know to go straight into making small beginner projects, then read and trying to understand others codes then learn more as I go on . So could anybody recommend a guideline for the basics for learncpp.com? If the best way is to go through each chapter I'll just stick to that ig.
Granted I am currently about halfway through chapter 1 still but I just want to know more of the main things
As you know in Vscode with Python, we can create an virtual environment and choose this environment, the intellense works well.
But with C++, I need to use json files and manually add each .header files for intellense working. It is too tedious and not effective, especially in the case with many header files.
Could you share how do you config for intellense in Vscode?
I know that in C++ var has specific type at initial time.
But when debugging in VScode, in watch out window, I can not know how to variable type and also attributes, methods of objects. It is difficult for me to debug large projects (I am a newbie with C++) ==> I can not trace value of variables. With Python, it is easy.
Could you me give me some advice?
I'm curious what everyone thinks. I think I lean towards cpp reference but I use both
Was tutoring someone who was accessing a library called "adt_set.h" and "adt_queue.h"
I've never seen these libraries, they told me its just what the grading website uses, and that the instructor just included it for them. I can't find them online, does anyone know where to find these?
As the title suggests, I'm an experienced, professional developer (go, rust, python, etc) but haven't touched C++ in twelve years. From what little I've watched the language over the years I know its changed quite a bit in that time.
I'm looking for resources (print or digital) targeted to this demographic, on all things modern C++:
I'll be mostly focusing on embedded linux development, but any suggestions are welcome.
hey guys, hopefully someone can guide me.
I built my program on mac with 2 lines to install both sdl and sdl_ttf and it works right away andi started working on my mac.
I try to run the same program on my windows machine and installing sdl2 is proving to be impossible.
I have downloaded the dev package and placed them in my home directory. I have linked them, tried linking them directly, tried everything I can think of and I just get error after error.
is there some easy way to install sdl2 on windows that won't mess up my mac file.
After 20 mins with pasting the error into chatgpt ad doing what it says I have ended up with a much larger cmakelist
I can verify the files i have linked directly are present in the directories i have listed. Now chatgpt is just going in circles, in one case sayiong that ttf needs to be linked before sdl and then when that errors it says sdl needs to be linked before ttf.
why is this so damn difficult? is it because I am using clion rather than visual studio? I just want to work on my project on both mac and windows. on mac it was a simple as running brew install and it was done. surely there is some way to make it work as easy on windows? i assume something needs to be added to path?
first time using C++ with SDL.
thank you for any tips or guidance.
cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
project(GalconClone)
if(WIN32)
set(SDL2_DIR "C:/Users/Home/SDL2/x86_64-w64-mingw32")
set(CMAKE_PREFIX_PATH ${SDL2_DIR})
# Removed the -lmingw32 linker flag to avoid multiple definitions of main
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -mconsole")
# Manually specify SDL2_ttf paths if not found automatically
set(SDL2_TTF_INCLUDE_DIR "${SDL2_DIR}/include/SDL2")
set(SDL2_TTF_LIBRARIES "${SDL2_DIR}/lib/libSDL2_ttf.dll.a")
endif()
find_package(SDL2 REQUIRED)
# Manually define SDL2_ttf if find_package fails
if (NOT TARGET SDL2::SDL2_ttf)
if(NOT SDL2_TTF_INCLUDE_DIR OR NOT SDL2_TTF_LIBRARIES)
message(FATAL_ERROR "SDL2_ttf library not found. Please ensure SDL2_ttf is installed and paths are set correctly.")
endif()
add_library(SDL2::SDL2_ttf UNKNOWN IMPORTED)
set_target_properties(SDL2::SDL2_ttf PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${SDL2_TTF_INCLUDE_DIR}"
IMPORTED_LOCATION "${SDL2_TTF_LIBRARIES}"
)
endif()
include_directories(${SDL2_INCLUDE_DIRS} ${SDL2_TTF_INCLUDE_DIR} include)
add_executable(GalconClone src/main.cpp src/Game.cpp src/Planet.cpp src/Fleet.cpp src/Ship.cpp)
target_link_libraries(GalconClone PUBLIC SDL2::SDL2 SDL2::SDL2main SDL2::SDL2_ttf)
the latest errors are
C:\Windows\system32\cmd.exe /C "cd . && C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin\g++.exe -g -mconsole CMakeFiles/GalconClone.dir/src/main.cpp.obj CMakeFiles/GalconClone.dir/src/Game.cpp.obj CMakeFiles/GalconClone.dir/src/Planet.cpp.obj CMakeFiles/GalconClone.dir/src/Fleet.cpp.obj CMakeFiles/GalconClone.dir/src/Ship.cpp.obj -o GalconClone.exe -Wl,--out-implib,libGalconClone.dll.a -Wl,--major-image-version,0,--minor-image-version,0 C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2.dll.a C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2_ttf.dll.a -lshell32 -Wl,--undefined=WinMain -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin/ld.exe: C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a(SDL_windows_main.c.obj):SDL_windows_ma:(.text+0x84): undefined reference to `SDL_strlen'
C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin/ld.exe: C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a(SDL_windows_main.c.obj):SDL_windows_ma:(.text+0xb0): undefined reference to `SDL_memcpy'
C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin/ld.exe: C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a(SDL_windows_main.c.obj):SDL_windows_ma:(.text+0xb8): undefined reference to `SDL_free'
C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin/ld.exe: C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a(SDL_windows_main.c.obj):SDL_windows_ma:(.text+0xce): undefined reference to `SDL_wcslen'
C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin/ld.exe: C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a(SDL_windows_main.c.obj):SDL_windows_ma:(.text+0xe6): undefined reference to `SDL_iconv_string'
C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin/ld.exe: C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a(SDL_windows_main.c.obj):SDL_windows_ma:(.text+0x10c): undefined reference to `SDL_ShowSimpleMessageBox'
C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin/ld.exe: C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a(SDL_windows_main.c.obj):SDL_windows_ma:(.text+0x146): undefined reference to `SDL_SetMainReady'
C:\Users\Home\AppData\Local\Programs\CLion\bin\mingw\bin/ld.exe: C:/Users/Home/SDL2/x86_64-w64-mingw32/lib/libSDL2main.a(SDL_windows_main.c.obj):SDL_windows_ma:(.text+0x152): undefined reference to `SDL_main'
Hello my fellow colleagues. I hope everyone is having a great start to their Monday's.
This is my first post on r/Cplusplus and I've been waiting to release this publicly until I felt it was ready for use / contributions.
I've created 2 open sourced projects
1) The Beldum Package Manger:
https://github.com/Nord-Tech-Systems-LLC/beldum_package_manager
2) A C++ Backend Webserver (under construction, but working enough to play around with):
https://github.com/Nord-Tech-Systems-LLC/cpp_webserver
Prior to responses on this thread I would like to address a few things that I know are going to be commented on, so here is a bit of a FAQ:
I understand the learning curve associated with learning C++, and it seems like the package managers associated with C++ do not provide a simple way to practice and test simple C++ libraries. There are usually difficult or cumbersome processes associated with trying to test a package, and a deep understanding of linux directory structures.
What I've done is taken a complex task such as installing a library and made it similar to that of `npm` or `yarn`, where all of the details of how the package is handled is abstracted for new users.
In today's world, we all want the fastest product -- I get it; this is not meant to be the fastest library on the market, nor is it striving to be. It is for new users to test and learn C++ so they are not discouraged away from learning C++. I feel C++ is quickly losing it's userbase. This is my attempt at trying to revitalize the language for our new users today.
C++ is a great language. I understand that a lot of people have issues with the language itself that are deep rooted in decades of programming, but there is a large set of infrastructure that is built on the C and C++ languages. C++ is powerful, and I know there are lots of innovative C++ programmers (new and old) who have the capabilities to help drive C++ into the future.
Beldum package manager provides a template of how you would import the libraries, giving the new users a chance to see how it should work, with a predefined build script that they can mess around with, to make learning CMake not as difficult or such a high learning curve.
Please, can we have this discussion be productive and constructive?
Lastly,
It's nice to meet the C++ community. I hope to make future contributions as well.
C++ is my chosen career language.
Thank you,
VikingOfValhalla
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.
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.
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
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?
I am making a Fetch script like Neofetch using C++ and wanted to left align the information. Although I am unable to achieve this.
```#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
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
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.