/r/cpp_questions
a subreddit for c++ questions and answers
This is a subreddit for c++ questions with answers. For general discussion and news about c++ see r/cpp.
New to C++? Learn at learncpp.com
Prepare your question. Think it through. Hasty-sounding questions get hasty answers, or none at all. Read these guidelines for how to ask smart questions.
For learning books, check The Definitive C++ Book Guide and List
Flair your post as SOLVED if you got the help you were looking for! If you need help with flairs, check out ITEM 1 in our guidelines page.
Tips for improving your chances of getting helpful answers:
/r/cpp_questions
I've followed the instructions for building Kodi here: Compiling Kodi but it always fails at 100% :
[100%] Generating AddonModuleXbmcwsgi.i.cpp
Problem while looking for clang-format in Chromium source tree:
Could not find checkout in any parent of the current path.
Set CHROMIUM_BUILDTOOLS_PATH to use outside of a chromium checkout.
make[2]: *** [build/swig/CMakeFiles/python_binding.dir/build.make:119: build/swig/AddonModuleXbmcwsgi.i.cpp] Error 1
make[2]: *** Deleting file 'build/swig/AddonModuleXbmcwsgi.i.cpp'
make[1]: *** [CMakeFiles/Makefile2:13011: build/swig/CMakeFiles/python_binding.dir/all] Error 2
make: *** [Makefile:146: all] Error 2
And I can't figure out why it's happening.. I've searched to see if Kodi requires Chromium source but it doesn't say anywhere that it's required. Surely if Chromium was a dependency, the readme would have mentioned it, right?
The message mentions an AddonModuleXbmcwsgi but there is no cmake option to disable this "addon".
If anybody has built Kodi on Linux before, I'd sure like to know why it's failing here!
Thanks
SOLVED
I started c++learning today with this youtube video
https://www.youtube.com/watch?v=8jLOx1hD3_o&t=2037s&ab_channel=freeCodeCamp.org
during 40:13 minutes i tried to make exe file name rooster and got this error
cmd /c chcp 65001>nul && C:\mingw64\bin\g++.exe -g -std=c++20 C:\c++learning\*.cpp -o C:\c++learning\.vscode\rooster.exe
cc1plus.exe: fatal error: C:\c++learning\*.cpp: Invalid argument
compilation terminated.
I used 'visual studio code ' and 'mingw64' from winlib
These are the 2 codes that I used.
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "Build with GCC 14.2.0",
"command": "C:\\mingw64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"-std=c++20",
"${workspaceFolder}\\*.cpp",
"-o",
"${fileDirname}\\rooster.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "compiler: C:\\mingw64\\bin\\g++.exe"
}
]
}
#include <iostream>
int main(){
auto result = (10 <=> 20) > 0;
std::cout << result << std::endl;
}
Should i make notes when I'm reading programing and principles book by bjourne and if yes then how to make the notes any tips will be appreciated ✅
When do you think i should make projects rn I'm reading book called programming and principles by bjourne
Hi, I recently moved from Visual Studio to CLion. For my new project I need to use the libcurl library, which I tried to install with the vcpkg interation in CLion, but CMake doesn't seem to find the library.
Anyone knows how to fix this?
I was making c++ code using std::upper_bound() and I had to make my own comparator. Well, I used to make my own comparator for std::lower_bound() so I made same comparator for std::upper_bound() too. But the code didn't work. And I found out that std::lower_bound() and std::upper_bound() have different comparator methods. Like the code below
#include <iostream>
#include <algorithm>
#include <vector>
struct s {
int a;
int b;
};
std::vector<s>v;
bool ubcmp(const s& p, const int& element) {
return p.a < element;
}
bool upcmp(const int& element, const s& p) {
return element < p.a;
}
// Different methods!
int main()
{
v.push_back({1,0});
v.push_back({2,0});
v.push_back({2,0});
v.push_back({3,0});
v.push_back({4,0});
v.push_back({6,0});
int num = 2; // aim num
int lbi = std::lower_bound(v.begin(),v.end(),num,ubcmp)-v.begin();
int ubi = std::upper_bound(v.begin(),v.end(),num,upcmp)-v.begin();
std::cout << lbi << " " << ubi;
// result: 1 3
}
Can someone explain me why did developers make them different?
My post got deleted in r/cpp lol
This is my second post in reddit
Hi I am very new to C++ and just trying to setup everything following a tutorial, I have installed everything and was just checking if everything works
I have the following code(see below) but when I run it I receive an error
My GCC VERSION IS 14.2.0 and the tutorial i am following the instructor is using 11. something version, i tried using -std:c++26 but it keep giving me error what could be the possible solution?
#include<iostream>
int main(){
auto result = (10 <=> 20) > 0;
std::cout<< result << std::endl;
}
the error i receive is:
g++.exe: error: unrecognized command line option '-std=c++20'; did you mean '-std=c++03'?
Hi , this is a bit cmake related but since most CPP projects are built using cmake , maybe it's a bit relevant , do you guys know of a tool that can analyze and browse a cmake graph dependencies ?
For example , to find cycles in the graph?
I'm interested in developing a tool specifically for this , something better than dumping all .dot files to an image to view the graph , especially if the whole project has hundreds of dependencies that method becomes unusable.
If you guys don't know about such a tool, as C++ devs would you be interested in a fast program that could do this ?
What kind of additional features would you like for it than simply viewing the graph in high resolution , finding cycles , links , etc ?
I want to build a cross-platform mobile app, that will detect and track moving objects in real-time. Because it's a mobile app and in real-time, I decided to go with C++, which will handle the algorithms running in the back-end for object tracking. However, I am unsure what to create the user interface with. Does it affect performance what language/framework I go with? for example if I use React Native, Flutter with C++, or Android Studio (not cross-platform but I can deal with it if needed). Or should I stick to C++ even for the front-end, and use something like Qt, which I have zero experience with.
Bypassing the USB protocol
write(USB_PORT_3, HIGH)
read(USB_PORT_3) -> LOW
Is there a driver I can just install that will give me that functionality? Other answers say it's possible with a custom kernel driver.
Hey guys, little background first. I'm a non CS grad who does programming. I've learnt basics of Cpp and done a minor projects for my own.
What habits and best practices I should follow to work in a team as I feel best way to learn this is by doing.
I use vscode. Haven't tried CMake, version control etc.
Kind suggestions to books and resources highly appreciated.
I'm learning C++ coming from a background of 15 years of Python programming and a couple years of C programming. I wanted to implement a CLI in a project recently, and I wanted something similar to the ArgumentParser class in Python, so I wrote this OptionParser class. The problem is that I want to be able to support more than just a few built in types, but I'm not sure how to go about it.
Right now I'm using an enum to tell the class what parser function to use, and the class has a map for each supported data type. Then the parseOptions
function uses getopt_long and parses each of the inputs depending on the associated enum value. Finally, the overloaded getOptionValue
function is used to retrieve the value.
Here is the code.
OptionParser.h:
#ifndef OPTIONPARSER_H
#define OPTIONPARSER_H
#include <cstddef>
#include <string>
#include <complex>
#include <map>
#include <vector>
#include <getopt.h>
const size_t MAX_LONGNAME_LENGTH = 20;
enum OptionType {
DOUBLE_TYPE,
COMPLEX_DOUBLE_TYPE,
SIZE_T_TYPE,
UINT32_T_TYPE,
STRING_TYPE,
};
class OptionParser {
public:
OptionParser(std::string progName);
void addDescription(std::string description);
void addEpilog(std::string epilog);
bool addOption(char shortName, std::string longName, std::string helpMsg, enum OptionType t);
bool parseOptions(int argc, char **argv);
bool getOptionValue(std::string longName, std::string &out);
bool getOptionValue(std::string longName, double &out);
bool getOptionValue(std::string longName, std::complex<double> &out);
bool getOptionValue(std::string longName, size_t &out);
bool getOptionValue(std::string longName, uint32_t &out);
private:
struct Private;
std::string progName;
std::string description;
std::string epilog;
std::map<std::string, char> longToShort;
std::vector<struct option> options;
std::string shortOpts;
std::map<std::string, std::string> helpMessages;
std::map<char, enum OptionType> optionTypes;
std::map<char, std::string> stringOptions;
std::map<char, double> doubleOptions;
std::map<char, std::complex<double>> complexDoubleOptions;
std::map<char, size_t> sizetOptions;
std::map<char, uint32_t> uint32tOptions;
};
#endif
OptionParser.cpp:
#include "OptionParser.h"
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <iostream>
#include <getopt.h>
using namespace std;
static bool parse_size_t(const char* str, char name, size_t &value){
char *end = nullptr;
errno = 0;
size_t result = strtoul(str, &end, 0);
if(errno == ERANGE) {
fprintf(stderr, "Value for option -%c is too large.\n", name);
return false;
}
else if(errno == EINVAL) {
fprintf(stderr, "Value for option -%c has no valid characters.\n", name);
return false;
}
else if(*str != '\0' && *end == '\0') {
value = result;
return true;
}
else {
fprintf(stderr, "Value for option -%c contains invalid characters.\n", name);
return false;
}
}
static bool parse_uint32_t(const char *str, char name, uint32_t &value){
size_t result;
if(parse_size_t(str, name, result) && (result <= UINT32_MAX)){
value = (uint32_t)result;
return true;
}
else {
fprintf(stderr, "Value for option -%c is too large.\n", name);
return false;
}
}
static bool parse_double(const char *str, char name, double &value) {
char *end = nullptr;
errno = 0;
double result = strtod(str, &end);
if((errno == ERANGE) && (result == HUGE_VAL)){
fprintf(stderr, "Value for option -%c is too big.\n", name);
return false;
}
else if (errno == ERANGE){
fprintf(stderr, "Value for option -%c is too small.\n", name);
return false;
}
value = result;
return true;
}
static bool parse_complex_double(const char *str, char name, complex<double> &value) {
size_t input_len = strlen(str);
char *input = (char *)calloc(input_len+1, 1);
memcpy(input, str, input_len);
char *part = strtok(input, ",");
double real_part;
if(!parse_double(part, name, real_part))
return false;
part = strtok(nullptr, ",");
double imag_part;
if(!parse_double(part, name, imag_part))
return false;
value = {real_part, imag_part};
free(input);
return true;
}
struct OptionParser::Private {
static void usage(OptionParser &self) {
// Prints a help message generated from the option data supplied.
cout << self.progName << ' ';
for(const auto &kv : self.longToShort) {
cout << "[-" << kv.second << ' ';
for(const auto &c : kv.first) {
cout << (char)toupper(c);
}
cout << "] ";
}
cout << endl;
if(self.description.length()){
cout << self.description << endl;
}
cout << endl;
cout << "Option Details:" << endl;
for(const auto &kv : self.longToShort) {
cout << " ";
cout << '-' << kv.second << ' ';
cout << "--" << kv.first;
for(int i=0; i< (MAX_LONGNAME_LENGTH - kv.first.length() + 1UL); i++){
cout << ' ';
}
cout << self.helpMessages[kv.first] << endl;
}
if(self.epilog.length()){
cout << endl << self.epilog << endl;
}
}
};
OptionParser::OptionParser(string progName) {
// Initialize the OptionParser with a name that is shown in the help message.
this->progName = progName;
// By default any OptionParser can print a help message,
// so their needs to be a corresponding option for getopt_long.
struct option helpOp = {
.name = "help",
.has_arg = no_argument,
.flag = nullptr,
.val = 'h'
};
options.push_back(helpOp);
// The short option string for getopt_long.
// Leading + tells getopt_long to stop processing when an error is encountered.
// Leading : (after the +) tells getopt_long to signal the difference bewteen a
// missing expected argument and an unknown argument.
shortOpts += "+:h";
}
void OptionParser::addDescription(string description) {
// Add an optional description to the help output.
this->description = description;
}
void OptionParser::addEpilog(string epilog) {
this->epilog = epilog;
}
bool OptionParser::addOption(char shortName, string longName, string helpMsg, enum OptionType t) {
// adds an option to be parsed.
// Example : parser.addOption('f', "foo", "Computes foo.", SIZE_T_TYPE);
// This means the parser expects either -f or --foo in the arguments.
// The foo option is parsed as a size_t and stored in the size_t map.d
if(longToShort.find(longName) != longToShort.end()){
return false;
}
if(longName.length() > MAX_LONGNAME_LENGTH){
return false;
}
struct option op = {
.name = longName.c_str(),
.has_arg = required_argument,
.flag = nullptr,
.val = shortName,
};
helpMessages[longName] = helpMsg;
longToShort[longName] = shortName;
optionTypes[shortName] = t;
options.push_back(op);
shortOpts += shortName;
shortOpts += ':';
return true;
}
bool OptionParser::parseOptions(int argc, char **argv){
struct option blankOption = {
.name = nullptr,
.has_arg = 0,
.flag = nullptr,
.val = 0
};
options.push_back(blankOption);
int ch;
const char *shortOptsCStr = shortOpts.c_str();
while((ch = getopt_long(argc, argv, shortOptsCStr, options.data(), nullptr)) != -1) {
switch(ch){
case ':':
cout << "Missing value for option " << (char)optopt << endl;
return false;
case '?':
cout << "Invalid option: " << (char)optopt << endl;
return false;
case 'h':
Private::usage(*this);
return false;
default:
break;
}
switch(optionTypes[ch]){
case DOUBLE_TYPE: {
double result;
if(parse_double(optarg, ch, result)){
doubleOptions[ch] = result;
}
else {
return false;
}
break;
}
case COMPLEX_DOUBLE_TYPE: {
complex<double> result;
if(parse_complex_double(optarg, ch, result)){
complexDoubleOptions[ch] = result;
}
else {
return false;
}
break;
}
case SIZE_T_TYPE: {
size_t result;
if(parse_size_t(optarg, ch, result)){
sizetOptions[ch] = result;
}
else {
return false;
}
break;
}
case UINT32_T_TYPE: {
uint32_t result;
if(parse_uint32_t(optarg, ch, result)){
uint32tOptions[ch] = result;
}
else {
return false;
}
break;
}
case STRING_TYPE:
// no parsing to do
stringOptions[ch] = optarg;
break;
default:
fprintf(stderr, "Invalid type enum for option %c.\n", ch);
break;
}
}
return true;
}
static bool lookUp(map<string,char> m, string k, char &out){
auto findResult = m.find(k);
if(findResult == m.end()){
return false;
}
out = findResult->second;
return true;
}
bool OptionParser::getOptionValue(string longName, string &out){
char shortName;
if(!lookUp(longToShort, longName, shortName)){
return false;
}
auto result = stringOptions.find(shortName);
if(result == stringOptions.end()){
return false;
}
out = result->second;
return true;
}
bool OptionParser::getOptionValue(string longName, double &out){
char shortName;
if(!lookUp(longToShort, longName, shortName)){
return false;
}
auto result = doubleOptions.find(shortName);
if(result == doubleOptions.end()){
return false;
}
out = result->second;
return true;
}
bool OptionParser::getOptionValue(string longName, complex<double> &out){
char shortName;
if(!lookUp(longToShort, longName, shortName)){
return false;
}
auto result = complexDoubleOptions.find(shortName);
if(result == complexDoubleOptions.end()){
return false;
}
out = result->second;
return true;
}
bool OptionParser::getOptionValue(string longName, size_t &out){
char shortName;
if(!lookUp(longToShort, longName, shortName)){
return false;
}
auto result = sizetOptions.find(shortName);
if(result == sizetOptions.end()){
return false;
}
out = result->second;
return true;
}
bool OptionParser::getOptionValue(string longName, uint32_t &out){
char shortName;
if(!lookUp(longToShort, longName, shortName)){
return false;
}
auto result = uint32tOptions.find(shortName);
if(result == uint32tOptions.end()){
return false;
}
out = result->second;
return true;
}
Hi, my group and I are working on a C++ project to create a transport management system. We have developed an interface for the bus driver, and in the driver's menu, I want to add an option for the driver to view the route they need to take. Is there a way to include a link in Dev-C++ that opens the Google Maps app, allowing the driver to click 'Start' and begin their pre-set route? Also, please suggest an easy way to do this since we are just in our first year of college and have been learning C++ for only three months. If there’s a C++ library or something similar that could help, that would be great.
Hi,
I'm trying to add OpenTelemetry to an existing codebase, which is very large and old--the thing is, it already uses Google Protobuf, and it is extremely difficult to update it (requires refactoring a protobuf plugin).
OpenTelemetry is a library that uses GRPC, which in turn uses Protobuf. It's unfeasible to either point GRPC at an ancient protobuf or update the codebase to use the latest protobuf without risking serious bugs, so I'm at a loss due to linking errors.
My understanding of linking is that two libraries cannot link to the same executable at the same stage without causing a redeclaration issue.
But I understand that this can be avoided if the linking occurs separately. As the linking occurs when building a shared library, I figured that if I compile GRPC statically, and then compile OpenTelemetry as a shared library, I could in turn link it to the project.
However, I am running into a heap of trouble trying to get this to work. I'm getting scores of rows such as this:
/usr/bin/ld: /root/.local/lib/libopentelemetry_exporter_otlp_grpc_log.so: undefined reference to `opentelemetry::v1::exporter::otlp::GetOtlpDefaultLogsHeaders[abi:cxx11]()'
Currently, the CMake module I'm trying to add it to looks like this. Forgive the mess, just testing things with little care for form.
CollectIncludeDirectories( ${CMAKE_CURRENT_SOURCE_DIR} PUBLIC_INCLUDES # Exclude ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) target_include_directories(common PUBLIC # Provide the binary dir for all child targets ${CMAKE_BINARY_DIR} ${PUBLIC_INCLUDES} "/root/.local/include" PRIVATE ${CMAKE_CURRENT_BINARY_DIR} # ${OPENTELEMETRY_CPP_INCLUDE_DIRS} )
target_link_libraries(common PRIVATE core-interface PUBLIC argon2 boost fmt g3dlib "/root/.local/lib/libopentelemetry_common.so" "/root/.local/lib/libopentelemetry_exporter_in_memory_metric.so" "/root/.local/lib/libopentelemetry_exporter_in_memory.so" "/root/.local/lib/libopentelemetry_exporter_ostream_logs.so" "/root/.local/lib/libopentelemetry_exporter_ostream_metrics.so" "/root/.local/lib/libopentelemetry_exporter_ostream_span.so" "/root/.local/lib/libopentelemetry_exporter_otlp_grpc_client.so" "/root/.local/lib/libopentelemetry_exporter_otlp_grpc_log.so" "/root/.local/lib/libopentelemetry_exporter_otlp_grpc_metrics.so" "/root/.local/lib/libopentelemetry_exporter_otlp_grpc.so" "/root/.local/lib/libopentelemetry_logs.so" "/root/.local/lib/libopentelemetry_metrics.so" "/root/.local/lib/libopentelemetry_otlp_recordable.so" "/root/.local/lib/libopentelemetry_proto_grpc.so" "/root/.local/lib/libopentelemetry_proto.so" "/root/.local/lib/libopentelemetry_resources.so" "/root/.local/lib/libopentelemetry_trace.so" "/root/.local/lib/libopentelemetry_version.so" )
I am at my wits end and don't know where else to go, honestly. I at first tried commands like add_library(opentelemetry-cpp SHARED IMPORTED)
, but it raises errors of its own. I also tried using find_package and just letting CMake sort it out itself using the ~/.local/lib/cmake
cmake options, but it appears to try to compile it or something as it starts demanding linkages to abseil and protobuf even though OpenTelemetry was compiled as a shared binary, which I understand would mean abseil and protobuf should be embedded inside OpenTelemetry's .so files.
If anyone can at least affirm that what I'm setting out to do is feasible? I should be able to link a library that uses Google Protobuf using CMake in such a way that it doesn't conflict with my own application's use of Protobuf, yes?
If anyone has any insights I'd be eternally thankful,
Thanks!
Edit: If anyone's curious what exactly is the error when I use a find_package(opentelemetry-cpp CONFIG REQUIRED)
to do it instead of forcefully linking the .so files:
CMake Error at /root/.local/opentelemetry-cpp/lib/cmake/opentelemetry-cpp/opentelemetry-cpp-target.cmake:91 (set_target_properties): The link interface of target "opentelemetry-cpp::common" contains:
absl::strings
but the target was not found. Possible reasons include:
* There is a typo in the target name. * A find_package call is missing for an IMPORTED target. * An ALIAS target is missing.
Call Stack (most recent call first): /root/.local/opentelemetry-cpp/lib/cmake/opentelemetry-cpp/opentelemetry-cpp-config.cmake:92 (include) src/common/CMakeLists.txt:39 (find_package)
Edit 2: Incredibly, incredibly dumb move by me. Before I decided to go the static->shared route, I was reading some comments about how to "hide" the symbols, which suggested... yeah, this....
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden")
So this was edited into the CMakeLists.txt of opentelemetry. Woops... :)
Guys I'm newbie to coding on 500th page of programming and principles by bjourne and I've a problem here when i read and understand a chapter its fine but when it comes to exercises i always need chatgpt help but i want to improve myself abt me i read chapter and understand it i dont make notes does 4 questions but with chat gpt help please give me some good tips
I have previous experience with python at intermediate level. I want to learn cpp but idk where I should start, or whether I should actually learn cpp or not. I’m starting my cs degree next year and want to have at least sone experience with cpp since it’s quite a low language. (Ik its not THAT low but I’m not learning C💀).
Tldr; Where should I start
Guys I am learning cpp through learncpp.com website and I am finding difficulty in understanding the multifile thing (Lesson 2.8,2.10) I even changed from vscode to visual studio 2022 can anyone suggest me some video tutorials for the same.
Or can someone help me out resolving my confusion
/*main.cpp*/
#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.
#include <iostream>
int main()
{
std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
return 0;
}
/*add.cpp*/
#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.
int add(int x, int y)
{
return x + y;
}
I copied this code from the website itself and made two files seperately named main.cpp and add.cpp in the solution explorer section, but the thing is code won't compile for some reason and will give errors like cannot open source file "add.h" and "Cannot open include file: 'add.h': No such file or directory"
please help
Hey everyone,
I recently started learning C++ and have covered the basics. Now, I’m moving on to Data Structures and Algorithms (DSA). I’ve been following tutorials and practicing alongside, but I want to pick up a good book to go deeper.
After some research, I found these recommendations:
I’m thinking of starting with CLRS and then moving to Robert Sedgwick’s book later. Does this sound like a good plan? Or is there any other book you'd recommend for someone at my level?
Thanks in advance! 😊
#include <iostream>
class Node {
public:
int value_;
static Node default_node_; // declared
Node(int a = 17) : value_(a) {}
};
int main() {
Node defined_node = {};
Node::default_node_ = {}; // defined
std::cou t<< defined_node.value_ << std::endl;
std::cout << defined_node.default_node_.default_node_.value_ << std::endl;
std::cout << "\n\n\n\n\njsdhgkahjgflahwef\nsdjfbhskajehfifjAK\nfjsenjnfsknlfkmef";
return 17;
}
>> no errors, and seemingly ran, but didn't print a single character. Not even that junk string
#include <iostream>
class Node {
public:
int value_;
static Node default_node_; // declared
Node(int a = 17) : value_(a) {}
};
Node::default_node_ = {}; // defined
int main() {
Node defined_node = {};
std::cou t<< defined_node.value_ << std::endl;
std::cout << defined_node.default_node_.default_node_.value_ << std::endl;
std::cout << "\n\n\n\n\njsdhgkahjgflahwef\nsdjfbhskajehfifjAK\nfjsenjnfsknlfkmef";
return 17;
}
>> this lead to an error:"this declaration has no storage class or type specifier" by VSCode extension
I'm a hobby programmer and a total newb, so please bear with me. I've finished(or skimmed through) one C book and two C++ books(one is some 400 p. book for C++ newbies, covering mostly grammar and the basics of OOP, and one about data structure and STL).
What little I think I knew was this: declaration is meaningless without a definition(definition is when the stack memory is allocated). For the non-static members of a class, they are declared in the class statement, and defined when a variable of that class type is actually created in a local scope. As for static members, you should define them individually to give them space in the memory. Which is what I think I did, but apparently it doesn't like it.
I've already looked through my books: It had nothing about statically declaring an object of a class in itself.
I searched the cpp reference page, the both of them: I didn't find the reason it doesn't work, and because the definition of the keyword "static" is too over the place, I couldn't understand it well either.
I wanted to search Google and Stack Overflow for answers, but I didn't know what even to search for.
I tried to get the answer from the GPT(unpaid version) too but it spewed contradicting words too much I just couldn't get anything useful from it,
I have been trying this since morning with no luck, The Cmake file gives me error:
Could not find a package configuration file provided by "fmt" with any of following names
I am following this tutorial: https://learn.microsoft.com/en-us/vcpkg/get_started/get-started-vscode?pivots=shell-powershell
Here is my CMake File, I even set the CMAKE_TOOLCHAIN_FILE manually in my CMakeLists.
cmake_minimum_required(VERSION 3.10)
set(CMAKE_TOOLCHAIN_FILE "D:/VCPKG/vcpkg/scripts/buildsystems/vcpkg.cmake")
project(fmtCmake)
find_package(fmt CONFIG REQUIRED)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PRIVATE fmt::fmt)
No matter what I try it fails at find_package. I even have the CMakePresets and CMakeUserPresets Json files.
I'm not sure whats wrong with the code im making, but i think i made some mistakes. I wanted for the pause system to work as soon as you enter the name input (I'm specifically made the code for a system calculator)
Heres the code:
#include <iostream>
#include <conio.h>
#include <cstdlib>
using namespace std;
int main(){
//6 is the variable
//7 is the variable that can store the operator
string name;
double num1,num2;
char op;
cout<<"Type your name here..."<<endl;
cin>>name;
cout<<"Hold on, please wait! . . . ."<<endl;
system(“cls”)
getch(); //pause system
This program takes in two integer arguments from the user and then prints the consecutive sum of all numbers between those integers inclusively. It works for several different values, but with the numbers -3 and -4 it returns 1098256912. The code is below:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int a = stoi(argv[1]);
int b = stoi(argv[2]);
if (a > b) {
int c = b;
b = a;
a = c;
}
//add code below this line
int sum;
int n;
if (a == b) {
sum = a;
cout << sum << endl;
}
else {
n = b - a + 1;
for (int i = 1; i < b; i++) {
sum = (n/2 * (a+b));
}
}
cout << sum;
//add code above this line
return 0;
}
In the following code (This is C++98) I have a function that deletes values of a plain text by placing the values that do match the code on a new text. Whenever I have tried the function it worked but then I tried other different values and it did not work.
What does cause the pointer to go mad?(if it is, I just simply assume)
I added some prompts(I'm learning and simply wanted the user to give more control over the data, if they wanted to continue deleting and such). Therefore there are times that I close the file early while also closing a file that I know is open. Are the times that I use (filevalue).close() making the pointer go places that it shouldnt?
Also, I add that I only seek help, I do not want anyone to do any work for me but an explanation or an example will help me greatly, thanks
PD: I had the function to be far more simpler and it didn't ask anything else, it simply deleted and it also worked but yeah, suddenly I get to it and now it doesn't work with some values.
bool borrarAlumno(){
ifstream original;
ofstream copia;
string respuesta,codigoBor,codigo,nombre,apellido1,apellido2,asignatura,nota1,nota2,nota3,notaFinal;
bool encontrado=false;
system("cls");
//Se debe de obtener el codigo, es algo elemental para encontrar el alumno
cout<<"\\nDebe de introducir el codigo del alumno que va a borrar: ";
codigoBor = codigoGen();
//Se abren los archivos
original.open("alumnos.txt");
copia.open("copia.txt");
if(original.fail()){
cout<<"\\nError al intentar abrir el archivo de lectura para borrar a un alumno";
}
if(copia.fail()){
cout<<"\\nError al intentar abrir el archivo copia para borrar un alumno";
}
while(original>>codigo>>nombre>>apellido1>>apellido2>>asignatura>>nota1>>nota2>>nota3>>notaFinal){
//En el caso de que se encuentre no se añade esa linea al archivo
if(codigoBor==codigo){
encontrado=true;
}//En el caso de que no se encuentre se añade al archivo
else{
copia<<codigo<<" "<<nombre<<" "<<apellido1<<" "<<apellido2<<" "<<asignatura<<" "<<nota1<<" "<<nota2<<" "<<nota3<<" "<<notaFinal<<"\\n";
}
}
//Tras tenerlo todo añadido se ofrece la posibilidad de continuar borrando en el mismo menu, si no se cierra el archivo
if(encontrado==true){
cout<<"Se ha borrado el alumno con el codigo: "<<codigoBor<<"\\n";
cout<<"Desea borrar otro alumno?(Si/no)\\n";
cin>>respuesta;
respuesta = mayus(respuesta);
while(respuesta != "SI" and respuesta != "NO"){
cout<<"\nSolo se admiten si o no como respuestas validas, por favor introduzca una de estas: ";
cin>>respuesta;
respuesta = mayus(respuesta);
}
if(respuesta == "SI"){
copia.close();
original.close();
remove("alumnos.txt");
rename("copia.txt","alumnos.txt");
return borrarAlumno();
}
else if(respuesta == "NO"){
copia.close();
original.close();
cout<<"\\nVolviendo al menu principal";
system("pause");
return 0;
}
}
else if(encontrado==false){
cout<<"No se ha podido borrar un alumno ya que no se ha encontrado ningun alumno con ese codigo\\n";
}
//Se cierra todo siempre antes de salir
original.close();
copia.close();
//Se renombra y se borra el archivo
remove("alumnos.txt");
rename("copia.txt","alumnos.txt");
return true;
}
So I have a function that loads a gltf scene and it loops through many types of resources in order to load the entire thing. Sometimes I do not know how many objects are going to be added to an array for some of the resources, so I have to use std::vector::push_back() every iteration.
Now, what I thought would be a good idea was to first add a default instance of an object to the array and then initialize its data by using std::vector::back(). This would only be beneficial if the object would be initialized directly on the new memory block that was allocated(or reserved) by push_back().
What I do is this: myVector.push_back(MyObject());
I thought this would solve it, but I started thinking that it might just create a temporary object and then copy the memory to the array block, which would not be ideal to say the least.
I did test using std::move and it seems to make the function slightly slower. But that does not really answer my question. I tried looking it up everywhere but I couldn’t find anyone who had already asked this (maybe I wasn’t wording it correctly). So I decided to ask here.
TL;DR: Does myVector.push_back(MyObject()); initialize the memory directly on the myVector memory block allocated with push_back()? Does it create a temporary MyObject instance and then copy it on the array? If it’s the latter, is there a way to initialize an object’s memory directly on the std::vector memory block, or should I just use std::move?
I'm refactoring old code to use enum class
es, and I've faced a problem(?). By default, enum class
es have an underlying type of int
, while regular enum
s have an implementation defined underlying type. The old enum
s don't have an explicit underlying type specified (for obvious reasons). Is there any risk of breaking binary compatibility by changing them?
Is it ever a good practice to define their constructors and methods in their own cpp file or is that just subjective and arbitrary?
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"-O2",
"-DNDEBUG",
"-ggdb",
"-pedantic-errors",
"-Wall",
"-Weffc++",
"-Wextra",
"-Wconversion",
"-Wsign-conversion",
"-Werror",
"-std=c++20",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
1)See this my task.json file(as suggested in learncpp.com). But I don't know why my VSCODE won't run in c++20 version. I have tried every other changes as said by chatgpt and all but it still won't
2)I can't run my task.json file it says"Code not supproted"
3)Can someone tell me how to split files of a program and how it looks so that i can know if it is correct
I'm specifically talking about the case where you emplace at the front or the middle. But lets assume we are only talking about front case.
// as before
std::vector<std::string> vs;
// add elements to vs
vs.emplace_back("1");
vs.emplace_back("2");
vs.emplace_back("3");
// add "xyzzy" to beginning of vs
vs.emplace(vs.begin(), "xyzzy");
Q1
I figure emplace doesn't replace/overwrite anything.
So if you use emplace element in the front, the rest of the elements gets shifted to the next index by one?
Q2
Does this create 2 new std::string
?
Because one temporary std::string for the "xyzzy" so that it can be moved-assigned to vs[0]
and one std::string in the vector for the "3" so that it can shift from vs[2]
to vs[3]
?
I am making my own game, and I have created a window. Now I want to add my own custom image as the background. Is there any way to do that. It has to be simple, very less code, and efficient. Any ideas or any tutorial you would recommend me.
I just learnt about clang-format yesterday and it's pretty neat. I'm writing my .clang-format
file referring their style options
I want the function definition parameters to be one-per-line if they are longer above a certain limit like:
void dfs (
vector<vector<int>> const &Adj,
vector<char> &visited,
vector<int> &componentTraversal,
const int currentNode
) {
// internal code
}
This is my .clang-format
file till now:
BasedOnStyle: LLVM
UseTab: Never
TabWidth: 4
IndentWidth: 4
ColumnLimit: 110
BreakBeforeBraces: Attach
AllowShortFunctionsOnASingleLine: Inline
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortIfStatementsOnASingleLine: AllIfsAndElse
IndentCaseLabels: true
And my related vscode settings.json
:
{
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "file",
"editor.detectIndentation": true,
"editor.insertSpaces": true,
"editor.comments.insertSpace": true,
"[makefile]": {
"editor.insertSpaces": false
},
"[c][cpp][makefile]": {
"editor.defaultFormatter": "ms-vscode.cpptools",
"editor.tabSize": 4
},
"C_Cpp.clang_format_style": "file",
"C_Cpp.clang_format_fallbackStyle": "none",
"C_Cpp.vcFormat.indent.preserveComments": true,
}
Also tell me more additions or suggestions for better configuration