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

I am considering using a Rasberry Pi as an SBC (single board computer) with Android O/S installed and programming with Embarcadero RAD Studio 10.2  (C++ builder). Is there a library or other means of using the GPIO of the Rasberry Pi and other hardware features of the SBC ?
0
Exploring SharePoint 2016
LVL 12
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

Question is related to C++ STL list::sort(Compare) where Compare is now a template.

I am looking for the correct syntax to override the list::sort(Compare) definition to work with list<pair<int, T> > definition.

//-The Compare Function

template<typename W>
bool weightsort(const pair<int, W> &node1, const pair<int, W> &node2)
{
    return (node1.second <= node2.second);
}


//- Abbreviated class definition containing  STL list definition and call to sort

template<typename T>
class Graph {
    ...
    vector<T> shortest_reach(int startId, T sigWeight) {
        ...
        list<pair<int, T> >                                       frontier;   //-Nodes currently on the Queue to be Explored.
        typename list<pair<int, T> >::iterator      fit;
        ...
            frontier.sort(weightsort);
        ...
    }
    ....
};


$ c++ program.cpp

error: no matching member function for call to 'sort'
            frontier.sort(weightsort);
            ~~~~~~~~~^~~~

usr/include/c++/v1/list:1059:14: note: candidate template ignored:
      couldn't infer template argument '_Comp'
        void sort(_Comp __comp);
             ^
/usr/include/c++/v1/list:1056:10: note: candidate function not viable:
      requires 0 arguments, but 1 was provided
    void sort();
         ^
0
I want to create a server(OS: CentOS) which will be acting as an interface to an Android app(client) and the database.

I am not much experienced in programming and I just want a little bit of guidance right now to get started.
I have decided that I want to program the server in C++(though it's not an easy language but I believe there's much more to learn while programming in C++)

The basic functionality I want from my server:
1. It will interact with the app via https.
2. The server and client(app) will communicate via REST APIs.

I want guidance in terms of the most stable and well documented external C++ libraries that I should use to program the above server(I've looked at zmq, libcurl, netlib-cpp but due to my lack of experience I don't even know if these are really related to my problem statement). Thanks in advance. Please feel free to attach any blog/article/video which might be relevant.
0
What is the issue with the above code and how would you fix it?
indentation does not matter in this code, ":=" denotes the substitution, and "=" is the equal comparator.

========
Initial state of an array "a":

[[2, NULL, 2, NULL],
 [2, NULL, 2, NULL],
 [NULL, NULL, NULL, NULL],
 [NULL, NULL, NULL, NULL]]

========
Main function:

FUNCTION foo()
    FOR y := 0 to 3
        FOR x := 0 to 3
            IF a[x+1][y] != NULL
                IF a[x+1][y] = a[x][y]
                    a[x][y] := a[x][y]*2
                    a[x+1][y] := NULL
                END IF
                IF a[x][y] = NULL
                    a[x][y] := a[x+1][y]
                    a[x+1][y] := NULL
                END IF
            END IF
        END FOR
   END FOR
END FUNCTION


What does the foo function do?

How could you make foo more generic? Can we have three possible generalization directions ?
0
I have an issue using an ADOQuery component with C++ builder.
If I execute a simple query "select * from Frames where FrameID = 1934411" the result is no record returned when Frames is a view.
However, if I copy the entire view contents into a table and then run the query against the table then the Record is found ?
The database is a Microsoft SQL Server version 12.0.5207.0

If I run the query on the view or the table using Microsoft SQL Server Management Studio then in both cases the record is returned.

Can this be fixed to use the view ?
0
Hello , i've the following routine :
int Asio_Send_Pck(int iSendt,int Lsocket,char * Lbuff,int Len)

{

    LSession* iTempLSession = reinterpret_cast<LSession*>(Lsocket);

    boost::asio::async_write(iTempLSession->socket() ,

                              boost::asio::buffer(Lbuff, Len),

                              boost::bind(&LSession::handle_write, 

                              iTempLSession,

                              boost::asio::placeholders::error,

                              iTempLSession->data,

                              iSendt

                              ));

    return 0;

};

Open in new window


But i always get an Invalid Arguments .

Here's my Lsession class :

class LSession
{
public:
  int readlen;
  int userdata;
  int deadtime;
  enum { max_length = 1024};
  char data_[max_length];
  
   LSession(boost::asio::io_service& io_service)
        : deadtime(0), socket_(io_service)
    {
        readlen = 0;
        userdata = 0;
    }

  ~LSession()
  {
	  socket_.close();
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {	  
    socket_.async_read_some(boost::asio::buffer(data_, max_length),
        boost::bind(&LSession::handle_read, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }

  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  { 
    if (!error)
    {
	
	  try
	  {
	  if(Callback_readdata!= NULL)
	  

Open in new window

0
Hello, are you able to help me in creating a function which will convert an enum value to an actual image in C++?
0
Hello ;
I want to design a GUI.my application is as bellow :
while compiling my program , a first interface is displayed : it is for user authentication, by validating this step ,another interface is displayed :this interface is devided into two screen  show(Splitter with two column) the second interface is combined : a menu , and a tree view .by clicking in one item , a data and controls are shown in the right of interface.
To do this application , did I need for SDI or MDI
Also how to navigate between the two interfaces (the authentication interface and the second interface), should I use two Documents ?
For the first interface , I just want a simple area which display the logo of company and an edit control for tapping the Password. but since compiling the project ,always a classic dialog box is shown (made by Microsoft ).
Is there any idea which clarify my needs.
Kindly.
0
I have a problem whit the LRESULT CALLBACK WndProc,
When i add LPARAM wp the wc give's me a error message, for get the callback functionality when selecting a drop menu item.



main.cpp: In function 'int WinMain(HINSTANCE, HINSTANCE, LPSTR, int)':
main.cpp:56:24: error: invalid conversion from 'LRESULT (__attribute__((__stdcall__)) *)(HWND, UINT, WPARAM, LPARAM, LPARAM) {aka long int (__attribute__((__stdcall__)) *)(HWND__*, unsigned int, unsigned int, long int, long int)}' to 'WNDPROC {aka long int (__attribute__((__stdcall__)) *)(HWND__*, unsigned int, unsigned int, long int)}' [-fpermissive]
     wc.lpfnWndProc   = WndProc;


#include <windows.h>

void AddMenus(HWND);
HMENU hMenu;

int ID_Save;
int wp;

const char g_szClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, LPARAM wp)
{
    
    
    switch(msg)
    {
        case WM_COMMAND:
        
        switch(wp)

        {
            case 1:
            MessageBeep(MB_OK);
            break;

        }


        case WM_ACTIVATE:
            AddMenus(hwnd);
            break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
        default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,  LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    

Open in new window

0
#include <iostream>
class A {
public:
    int ii = 20;
    A(int i = 200) {
        std::cout << "A() \n";
        ii = i;
    }
    A(const A& obj) {
        std::cout << "Copy Constructor\n";
    }
    A(A&& obj) noexcept {
        std::cout << "A(A&&)\n";
    }
};

void fun(A i) {
    std::cout << "Fun \n" << i.ii << std::endl;
}

int main(int argc, const char * argv[]) {
    fun(A(12)); // Why this is not calling move constructor.
    return 0;
}

Open in new window

0
JavaScript Best Practices
LVL 12
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

C++ add menu,
it seems ther is no problem but when the window is created the menu don't show on the screen.
do i need to add a redraw option ?

When i go the a other active window the menu is created. strains.

#include <windows.h>

void AddMenus(HWND);
HMENU hMenu;

int ID_Save;


const char g_szClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        
        case WM_CREATE:
            AddMenus(hwnd);
            break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
        default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    
    
    return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,  LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;
   
    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

    
    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", 

Open in new window

0
run in to a trobbel need a littel help to get the window working.

main.cpp: In function 'int WinMain(HINSTANCE, HINSTANCE, LPSTR, int)':
main.cpp:41:20: error: 'g_szClassName' was not declared in this scope
 wc.lpszClassName = g_szClassName;
                    ^~~~~~~~~~~~~
main.cpp:54:1: error: expected ';' before 'if'
 if(hwnd == NULL)
 ^~
The terminal process terminated with exit code: 1


#include <windows.h>

const char g_sgClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

    switch(msg)
    {
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
        PostQuitMessage(0);
        break;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
        
    }
    return(0);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow)
{

WNDCLASSEX wc;
HWND hwnd;
MSG Msg;

//Step 1: Registering the Window Class
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);


if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);

Open in new window

0
In a CTreeCtrl, does GetChildItem() returns not null, if there is no child?  Is ItemHasChildren() is required? My below code hangs.

HTREEITEM FindTreeItem(HTREEITEM hItem, LPDISPATCH disp)
{
         if (disp == (LPDISPATCH)m_TreeCtrl.GetItemData(hItem))
            return hItem;

      HTREEITEM hChildItem = m_TreeCtrl.GetChildItem(hItem);
      while (hChildItem)
      {
            if (disp == (LPDISPATCH)m_TreeCtrl.GetItemData(hChildItem))
                  return hChildItem;

            HTREEITEM hItemFound = FindTreeItem(hChildItem, disp);
            if (hItemFound)
                  return hItemFound;

            hChildItem = m_TreeCtrl.GetNextItem(hChildItem, TVGN_NEXT);
      }

       return NULL;
}
0
Hello, I'm wondering if anyone has any examples of how to create a C++ Program (the code) to convert:

Feet > Meters
Meters > Feet

Thanks.
0
Since VS 2013 in seems we can use VersionHelpers.h to allow us to ask which version of Windows we are running on.  I looks simple up thru Windows 7 -- but reading the documentation, once we get to Windows 8 or Windows 10, the doc starts talking about the need for a Manifest and mentions GUID.   Can somebody help me understand what is required to get this to work?   My goal: from a C++ program be able to detect if we are running on Windows 10 (or later).   Thanks.
0
Hello , I want to display two edit controls by clicking on button .
in te first one , the two edit control are hiding . just by clicking a button , those two edit controls will be shown .
Any help please !
0
Here is a question of C++ that I was practising on some other site. The code is given below. My code fails for multiple inputs. the output is only
clee olg  
 instead of
 clee olg
sho col
Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as space-separated strings on a single line.
INPUT-
The first line contains an integer, t (the number of test cases).
Each line  'i' of the subsequent lines contain a String,S
OUTPUT-
For each String S(where 0<= j<=N-1), print S's even-indexed characters, followed by a space, followed by S's odd-indexed characters.
.
Eg-
2
college
school
output-

clee olg
sho col
    
 int main() {
    int t;
    cin>>t;
    
    string str;
    vector<string>s_even;
    vector<string>s_odd;
    for(int i=0;i<t;i++)
    {
        getline(cin,str);
      
    for(int j=0;j<str.size();j++)
    {
        //s.push_back(str);
        if(j%2==0)
        { string  a;
         a=str[j];
            s_even.push_back(a);
            
        }
        else
        { string b;
         b= str[j];
            s_odd.push_back(b);
        }
    }
        
        
       copy(s_even.begin(),s_even.end(),ostream_iterator<string>(cout));
       
        cout<<" ";
       
        copy(s_odd.begin(),s_odd.end(),ostream_iterator<string>(cout));
        str.clear();
        s_odd.clear();
        s_even.clear();
        //cout<<endl;
    }
    return 0;
}       

Open in new window

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
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
Angular Fundamentals
LVL 12
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

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
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 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
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

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.