C++

57K

Solutions

24K

Contributors

C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.

Share tech news, updates, or what's on your mind.

Sign up to Post

This article is about the variadic template, which often is implemented in a way the compiler has to recurse through function calls and to create unneeded function. There's a way to avoid compile-time recursion using std::initializer_list.
0
I am learning C++. It is going really well. It is making other stuff I have done in programming really make sense. I was interested in getting started programming with C++ visually. I want to make a program that runs on Windows. I did not know where to get started. There is not a lot of info on the topic. I found a helpful video on YouTube that showed how to get set up. It leaves me off with code like so:
#include "MyForm.h"

using namespace System;
using namespace System::Windows::Forms;

[STAThreadAttribute]
int main(array<String^>^ args) {
	Application::EnableVisualStyles();
	Application::SetCompatibleTextRenderingDefault(false);
	Lotto1::MyForm form;
	Application::Run(%form);
	return 0;
}

Open in new window

I do not know how to continue from here. How would I add some code that performs something like writing a string like calculating with overloaded functions! If anybody has any examples I would greatly apreciate seeing them.
I want to make a program that calculates values for a sphere or a cylinder with an overloaded function like so:
#include <iostream>
#include "func.h"
using namespace std;

int main()
{
	double Pi = 3.14790;
	cout << "Enter a radius: ";
	double radius = 0;
	cin >> radius;
	
	cout << "The sphere = " << calcRound(Pi, radius) << endl;

	cout << "Do you want to calculate the a cylinder? (yes = y/no = n) ";
	char answer1 = 'n';
	cin >> answer1;

	if (answer1 == 'y')
	{
		cout << "Enter a height: 

Open in new window

0
Hello everyone, is there code to create your console, can you somehow link it to using commands from a file and pressing the enter key?
c ++

    #include <log.h>
    #include <cvar.h>
    #include <option.h>
    #include <stream.h>
    #include <xmpp.h>
    #include <xmpp_kb.h>
    #include <session.h>
    #include <threads.h>
    #include <lang.h>
    #include <tools.h>

    int main(int argc, char *argv[])
    {
        const char *exe_path = argv[0];

        cvar_init();

        cvar_parse_file("kb.cfg");

        if (cvar.g_language != NULL)
        {
            char *path;

            FORMAT(path, "kfg/dang/%s.kfg", cvar.g_language);
            cvar_parse_file(path);
            free(path);
        }

        char *token = NULL;
        char *online_id = NULL;
        char *cmdline = NULL;

        option_parse(argc, argv, &token, &online_id, &cmdline);

        /* Start */

        if (isatty(STDOUT_FILENO))
        {
        }

        /* End */

        idh_init();

        XMPP_REGISTER_QUERY_HDLR();
        XMPP_WF_REGISTER_QUERY_HDLR();

        int wfs = stream_connect(cvar.online_server,
                                 cvar.online_server_port);

        if (wfs > 0)
        {
            session_init(wfs, online_id);

            threads_init();

            xmpp_connect(token, online_id);

            threads_run(exe_path, cmdline);

            threads_quit();

            xmpp_close();

0
what is the best tool to do profiling for c++ multi threaded server daemon on Linux?

Complied program with -pg and the tried with gprof/gmon.out. Couldn't find call graph as per functions mentioned in my program. It has shown all low level api's call graph like string internals, memory allocations..etc.

Can someone suggest how to get call graph from gmon.out for multi threaded server daemon.

Any other tool(s)?
0
I have to support a Visual Studio 6 C++ file. I've extracted the code which has two projects. One is the code for a DLL and the other for a LIB file. In trying to compile as is, I get an error that says Link.exe couldn't load the LIB file.

Since c++ is not a language I've worked with before, what are the steps to compile. Is there a "make" process first? When I look at the dsp file, it says that it is not a valid file and to make and run.

I'm missing something pretty simple I'm sure. The program was written in the late 90's. I just want to convert it to Visual Studio 2010 or 2015.

I tried converting it to Visual Studio 10 but most of it is not translated. I've attached one .7z which contains two 7z project to expand into a c++ workspace.
0
I had this question after viewing Remote App failed to launch using MSTSCLib API.
I have to launch an application remotely. with the below lines of code able to connect remote  desktop. but not able to launch remote application
m_RemoteAppobj = m_RDPClient.get_RemoteProgram2();
m_RemoteAppobj.put_RemoteProgramMode(true);
m_RemoteAppobj.put_RemoteApplicationName(L"Notepad");
m_RemoteAppobj.put_RemoteApplicationProgram(L"C:\\Windows\\System32\\notepad.exe");
void CTestRdpNECTIDlg::OnConnectedMstscax1()
{
      try
      {
            LPCTSTR lpExecutablePath = L"C:\\Windows\\System32\\notepad.exe";
            LPCTSTR lpworkingdirectory = L"c:\\";
            int n=m_RDPClient.get_Connected();
            m_RemoteAppobj.ServerStartProgram(lpExecutablePath,L"",lpworkingdirectory,false ,L"ARGS",false );
      }
      catch(...)
      {
            wchar_t buf[256];
            memset(buf,0,sizeof(buf)/sizeof(wchar_t));
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                  NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                  buf, (sizeof(buf) / sizeof(wchar_t)), NULL);
            AfxMessageBox(buf);
      }
}
0
Write a program in C++ to compute student's total marks, highest score and grade per subject as well as the average grade
0
Hi

I am a beginner to the arduino. To cut a long story short I have the code Serial.read which appears to read the 8 bit ascii value of a character.. This value is read into an int variable called Byte Received

Later in the code there is this
   
    if(ByteReceived == '1') // Single Quote! This is a character.
    {
      digitalWrite(led,HIGH);
      Serial.print(" LED ON ");
    }
    
    if(ByteReceived == '0')
    {
      digitalWrite(led,LOW);
      Serial.print(" LED OFF");
    }

Open in new window

   
 

I do not understand the if statements e,g,
if(ByteReceived == '1')

Open in new window


ByteReceived is an int and a value of 0 is null and a value of 1 is start of heading. Why are we comparing to 0 and 1 and why is it a character comparison ?

Furthermore I never get LED ON or LED OFF displayed but an led which is not pin 13 does flash .


Any help is much appreciated

Thanks
0
I have three base Classes {Player,Weapon,Game} and one inherited Class Warrior from Player.

I would like to code function addWizard using function .I thought of dymanic casting,but I'm not sure how to start. Any help would be appreciated.

Notes:

*Each index in playersArray consists of pointers to class Player.

*If a player's name in a given index,oplayersArray equals to empty string, it indicates there's no player yet.

*I added the constructors of each Class Game and Player(the default only) and Wizard.

void addWizard(string const& playerName,string const& weaponName,
                       Target target, int hitstrength,int range);

GameStatus Game::addPlayer(const string playerName, const string weaponName,
                               Target target,int hit_strength)
    {   int count=0,place=0;
        if(this->countPlayers()>=maxPlayer)
        {
            throw GameFull();
        }
        for(int i=0;i<maxPlayer;i++)
        {
            if(playersArray[i]->getPlayerName()!="" &&
               playersArray[i]->isPlayer(playerName))
            {
                throw NameAlreadyExists();
            }
            if(playersArray[i]->getPlayerName()==""&& count==0)
            {
                count++;
                place=i;
            }
        }
        Weapon newWeapon(weaponName,target,hit_strength);
        Player newPlayer(playerName,newWeapon);
        *playersArray[place]=newPlayer;
        return SUCCESS;
    } 

Open in new window


Classes:

class Game {
        int maxPlayers;
        Player **playersArray;
}

class Player {
        string player_name;
        int level;
        int strength;
        Weapon player_weapon; }

//the inherited Class 

class Wizard : public Player {
    int range;
public:
    Wizard();
    Wizard (string const& name, Weapon const& weapon, int range);
}

Open in new window

Constructs:
Game::Game(int maxPlayer)
: maxPlayer(maxPlayer),playersArray(new Player*[maxPlayer])
{
    for(int i=0;i<maxPlayer;i++)
    {
        playersArray[i]=new Player;
    }
}

Player::Player():
        level(0),life(0),strength(0),place(0),player_name()
{
}

Wizard::Wizard(string const& name, Weapon const& weapon, int range) :
        Player(name,weapon),range(range){
    if (weapon.getTarget() == LIFE){
        throw IllegalWeapon();
    }
    if(range<0)
        throw InvalidParam();
}

Open in new window

0
How to avoid dll-Hijack issue  ?

We have a normal C++ MFC application but we kept a .dll file in the same path where our application resides. When we start the application the dll file present in the current directory also loaded and fall in an infinite loop and our real application is non-responsive because the name of the dll is one of the System module dll that is loaded by the framework from the system path.

The reason is it look in the currentdir instead of the system path on Priprity of Dll search.
How we can avoid this dll hijack issue in Windows ?

Means how to avoid the search of dll from current directory rather look at system path at first priority
0

Author Comment

by:Sudhansu Panda
I have added the following entry by opening the command prompt with Admin privileges

C:\windows\system32>REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
\Session Manager\KnownDLLs" /v dwmapi /t REG_SZ /d dwmapi.dll
ERROR: Access is denied.

Can you let me know how to add the dll names here in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
\Session Manager\KnownDLLs entry
0
LVL 31

Expert Comment

by:Zoppo
Yes, to enter information in the registry in HKEY_LOCALMACHINE someone usually needs to be an admin.

It wouldn't make much sense if any user could change this, because each malware running with user right could change it too.
0
Hello

is there a way to set gdb filename:line_number such that the filename is a path?

thanks
0
I have ported some code from an old application that I wrote years ago to receive IP4 multicast data on a local area network using Indy 9.

The same code using Indy 10 on C++ builder XE10.1 Berlin doesn't work. No data is received in the OnIPMCastRead event handler (the event handler isn't triggered).
I have confirmed with wireshark that the network traffic is there on 244.0.0.166 port 60 as per the attached wireshark trace.
My code is as follows and the configuration of the Indy 10 IdIPMCastClient component is shown in the attached image file.
Can anyone explain why it isn't working please ?

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <IdBaseComponent.hpp>
#include <IdComponent.hpp>
#include <IdGlobal.hpp>
#include <IdIPMCastBase.hpp>[embed=file 1332006][embed=file 1332007]
#include <IdIPMCastClient.hpp>
#include <IdSocketHandle.hpp>
#include <IdUDPBase.hpp>
#include <IdUDPServer.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:	// IDE-managed Components
	TIdIPMCastClient *IdIPMCastClient1;
	TButton *Button1;
	void __fastcall IdIPMCastClient1IPMCastRead(TObject *Sender, const TIdBytes AData,
          TIdSocketHandle *ABinding);
	void __fastcall Button1Click(TObject *Sender);
private:	// User declarations

Open in new window

0
std::function as a parrameter in delegate constructor
      i want to know why control does not goes to AB() if i passed abc(AB) in main() as control goes for initialization of i as 10 when abc(10) is passed

class abc { int i;

    std::function<void(void)>func = nullptr;
public: abc(){}
    abc(std::function<void(void)>&fb):func(fb){}

    abc(int i):i(i){}
};
void AB() { cout<< "fun_AB"; }

int main() { abc(AB); abc(10); }

Open in new window

0
I wish to send a message to all client connected to my server application which uses an Indy 10 TCP Server component in Embarcadero C++ builder  XE 10.2 .

I have written the following function  which is meant to iterate through all the client connections to my server but it doesn't work.

I need some help in how to iterate through the list returned by the  IdTCPServer1->Contexts->LockList()  function.
I have seen an example in Delphi but my attempt in translating to C++ builder doesn't work.


void TForm1::BroadcastMessage(UnicodeString mess)
{
	TList *ls;
	int n;
	TIdContext *c;

	try
	{
		ls = IdTCPServer1->Contexts->LockList();
                n = ls->Count;
		for(int i=0;i<n;i++)
		{
			c = (TIdContext *)(ls->Items[i]); // <------ This line  is where the coding is wrong
			c->Connection->IOHandler->WriteLn(mess);
		}
		IdTCPServer1->Contexts->UnlockList();
	}
	catch(...)
	{
		IdTCPServer1->Contexts->UnlockList();
	}
}
//---------------------------------------------------------------------------

Open in new window

0
I need some assistance in writing a TCP Server in Embarcadero C++ builder XE 10.1 using  an Indy 10 TCP server VCL control.
How do I accept a connection from a client when using an Indy 10 VCL control TIdTCPServer ?
I imagine that I need to write some code in the OnConnect Event handler although logically one might expect a "BeforeConnect"  event handler .I haven't found any methods anywhere in the AContext or its members called Accept() ?
Also, my understanding is that  when a connection is established, the Execute event is invoked which supplies an AContext parameter which equates to a thread. Can I let the Execute event handler terminate and have a separate thread that manipulates the saved value of the AContext parameter in a list. the separate thread would poll round each AContext in the list  to independently send/receive data to/from the remote clients ?
0
Good day! I'm trying to display an image in the Picture Control in the MFC with pixel data. Tell me what's wrong.

image = new DicomImage(str);
		
		image->setMinMaxWindow();
		Uint8 *pixelData = (Uint8 *)(image->getOutputData(8));
		if (pixelData != NULL){
			int w = image->getWidth();
			int h = image->getHeight();

			HBITMAP hBitmap = NULL;

			BITMAPINFOHEADER bmih;
			bmih.biSize = sizeof(BITMAPINFOHEADER);
			bmih.biWidth = 1024;
			bmih.biHeight = -512;
			bmih.biPlanes = 1;
			bmih.biBitCount = 8;
			bmih.biCompression = BI_RGB ;
			bmih.biSizeImage = 0;
			bmih.biXPelsPerMeter = 10;
			bmih.biYPelsPerMeter = 10;
			bmih.biClrUsed = 0;
			bmih.biClrImportant = 0;

			BITMAPINFO dbmi;
			ZeroMemory(&dbmi, sizeof(dbmi));  
			dbmi.bmiHeader = bmih;
			dbmi.bmiColors[0].rgbBlue = 0;
			dbmi.bmiColors[0].rgbGreen = 0;
			dbmi.bmiColors[0].rgbRed = 0;
			dbmi.bmiColors[0].rgbReserved = 0;
			void* bits = (void*)&(pixelData[0]); 

			// Create DIB
			HDC localDC = ::GetDC(NULL);
			hBitmap = CreateDIBSection(localDC, &dbmi, DIB_RGB_COLORS, &bits, NULL, 0);
			if (hBitmap == NULL) {
				::MessageBox(NULL, __T("Could not load the desired image image"), __T("Error"), MB_OK);
				return;
			}

			unsigned char* dest = new unsigned char[w*h];
			dest =	(unsigned char*)bits;
			const unsigned char* src  = pixelData;
			for (int j=0; j<w; j++){
				for (int i=0; i<h; i++, src++){
					*dest++ = *src;
					*dest++ = *src;
					*dest++ = *src;
				}
			}	

			

Open in new window

0
Hi everybody,

I have a question about in-class initialization and thread-safety. I searched a lot in the net about this but wasn't able to figure it out.

I (accidentally) found a IMO nice way to implement somehting like an instance counter using in-class initialization like this:
// sample 1 using a static class member
struct Test1
{
	static int current;
	int num{ current++ };
};

int Test1::current{ 0 };

// sample 2 using singleton desing pattern
struct Test2
{
	static int& current()
	{
		static int curr{ 0 };
		return curr;
	}

	int num{ current()++ };
};

Open in new window

Both methods work fine:
void foo()
{
	for ( int n = 0; n < 5; n++ )
	{
		std::cout << "T1: " << Test1{}.num << " T2: " << Test2{}.num << std::endl;
	}
}

// output is as expected:
// T1: 0 T2: 0
// T1: 1 T2: 1
// T1: 2 T2: 2
// T1: 3 T2: 3
// T1: 4 T2: 4

Open in new window

Now I'm curious if this is thread safe. I know the instantiation of current itself is thread-safe, but I'm not sure what's about the ++ operator call: especially in the second example I would guess the ++ called for the returned reference is not thread safe, but on the other side I think compilers do a lot of complicated things to make statics thread safe, so probably my suspection is wrong.

JFI: I'm not sure since which C++ standard this can be used, I use C++17 (VS 2017), but maybe it works with older versions too.

Does anyone of you know better?

Best regards,

ZOPPO
0
how to get the SwapTotal for solaris in C or C++?
0
Hi,
I am making a Doodle Jump game in c++ using sfml,
I started building the umlaut and decided to go with a STRATEGY pattern. I don't really know if this is the right choice.
I basically got to a point where I don't know how to continue,
please if someone could take a look at my UML and tell me what they think it will be greatly appreciated.



0
I have a DLL that is simply using some pretty common code to count files in a directory. On all our test computers, and 98% of people using it, there is no problem. But a few people experience a crash to desktop from this code. I am looking for some possibilities of why this could happen in these isolated cases.

Here is the code:
int FMSGaugeCallback::getFltPlnsInFolder(wchar_t szPath[MAX_PATH])
{
	WIN32_FIND_DATA		ffd;
	wchar_t				szFileName[MAX_PATH];
	HANDLE				hFind = INVALID_HANDLE_VALUE;
	DWORD				dwError = 0;
	wchar_t				szError[255];
	wchar_t				szDir[MAX_PATH];
	int					nLen = 0, nDir = 0, nCount = 0;

	if (!PathIsDirectory(szPath))
		return 0;

	PathAddBackslashW(szPath);
	swprintf(szDir, sizeof szDir,  L"%s*.pln", szPath);
	hFind = FindFirstFileW(szDir, &ffd);								// Open filefind
	if (INVALID_HANDLE_VALUE == hFind)								// if process fails record error
	{																// and discontinue function
		dwError = GetLastError();
		swprintf(szError, sizeof szError, ERR_SEARCH_FLT_PLNS, szPath,getLastWinError(dwError));
		writeToErrorLog(szError);
		return 0;
	}

	do																		
	{																		
		if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)					
		{
			nDir++;															// the flight plan array
		}
		else
		{//-
			nCount++;
			
		}//-
	} while (FindNextFileW(hFind, &ffd));

	FindClose(hFind);												// Close filefind
	return nCount;
}

Open in new window


It is crashing in the do while loop, not at FindFirstFile.

Any ideas?
0
I am working on developing a Linux app for iPhones that will tell the user about the phone's lock status i. e. whether the phone is locked to a carrier or not, when connected to system
Also, if the phone is locked to a carrier then it's ESN status will also be reported.

This will help user to know the status of the phone before purchasing a used device.

I am aware that there are multiple websites providing this service.
I want to integrate this feature in my app,

I am developing this app in C++ in Linux environment.
I want to know if there is any API available to integrate this feature in my app.
If the API is available then from where I can get it.
0
Hello

I run into this problem with C++ code when on WIndows only.
Severity      Code      Description      Project      File      Line      Source      Suppression State
Error      C2664      'DWORD GetFileAttributesW(LPCWSTR)': cannot convert argument 1 from 'const char *' to 'LPCWSTR'      

This is when reading a string path , converting to char and calling the GetFileAttributes function. I am on windows 10 and compiling for a 32 bit arch (x86)
myfunc(const std::string & path){
DWORD  fileAttr=
GetFileAttributes(path.c_str()); //error list above!
}

Is there a elegant way to handle this? I donot want to be caught up in too much windows specific tailoring too much since my code is supposed to cross compile and run on linux and osx.

I understand the general problem = it is looking for a LPCWSTR long ptr to a 2 byte char. But how can i get it to work inside a #ifdef _WIN32 tag ,so that it stops complaining?
0
ardunio on board memory manipulation have a arduino mega now what is the best way to do the following, i want to have the program running and then update the array on board the arduino with out reloading the program, so lest say i have an array with 10 numbers and depending on the feed back from the card i am going to change location #4 of the in the 10 mem locations that i have set up how is the best way to do this please from the code running on the pc , would i access the arduino then the mem location and go from there, any ideas in this correct direction would be helpful
0
I had this question after viewing Explorer.exe crashing.
Hi, I have a simular issue on Windows 2016 Server RDS. I however do not have Microsoft Visual C++ 2008 installed but I do have the x86 and x64 versions of 2010 and 2012 installed. Do you suggest that is is a general issue with the Microsoft Visual C++ software of specific for Microsoft Visual C++ 2008?

Error:
The program iexplore.exe version 11.0.14393.2007 stopped interacting with Windows and was closed. To see if more information about the problem is available, check the problem history in the Security and Maintenance control panel.
 Process ID: a54
 Start Time: 01d3ec5f951cd3ff
 Termination Time: 8
 Application Path: C:\Program Files (x86)\Internet Explorer\iexplore.exe
 Report Id: e0176242-5852-11e8-90fe-001dd8b74bda
 Faulting package full name:
 Faulting package-relative application ID:
0
Unable to Debugg C++ ATL dll in C# . The ATL dll is not getting loaded. C# aplication is loading a interop but no pdb for interop is getting created.
Please let me know how to resolve this issue.
0

C++

57K

Solutions

24K

Contributors

C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.