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

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
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
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
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
Dear experts,

Can some experts please refer a url for downloading 'dec-c++'.
It could be either a paid or a free version.

I am learner of C/c++ program, so i am happy to go with minimum cost to start the process with.

Thank you
0
I have the following variadic macro code in a file named main.cc

#define DEBUG_PRINTF(fmt, ...) \
    do { if (verbose_flag) {\
        time_t t;\
        struct tm *t_info;\
        char buff[80];\
        time(&t);\
        t_info = localtime(&t);\
        strftime(buff, sizeof(buff), "%I:%M:%S", t_info);\
        std::string str(buff);\
        std::cout << str << " S" << my_server_instance << " ";\
        printf(fmt,__VA_ARGS__);}} while (0)

when I use g++ version 2.95.3-5 in CYGWIN like g++ -std=c++11 main.cc -c -o main.o to compile it, I get the compile error badly punctuated parameter list in #define and the error line is at printf(fmt,__VA_ARGS__);}} while (0). I have tried to fix it but I have not succeeded. How can this problem be fixed. I would like your directions on this.
0
pc to usb development, using c++ as the back ground code. i  am just starting so i need to be pointed towards a good cheapish usb development board, not sure what software and how this operates,
also some good reading materials, have down loaded a few books on the subject but not sure were to start.
at the moment all i need to do is to send some code to a board and turn some leds on and off just to get the code started
any help would be appreciated
0
I have a GUI with many buttons and other controls in it.   I have a long-running ( 10 seconds ) algorithm that gets launched in some situations.  While it is running, I don't want the user to poke any of the GUI buttons or controls.   I can put code at the top of each handler to check if its OK or not -- but, as there are many controls, this is a bit onerous.   So, I was wondering if there is some 'global' way that I can temporarily disable the GUI?    Suspend the windows message loop?    My world is:  MS  MFC   VC++

Thanks for ideas.
0
Using C++11:

I am trying to determine how to handle domain and range errors using the g++ compiler (Mingw64). I have provided some sample code below which is the approach that I use for g++ on Linux systems. When I compile I get the following messages:

warning: ignoring #pragma STDC FENV_ACCESS [-Wunknown-pragmas] #pragma STDC FENV_ACCESS ON
error: 'math_errhandling' was not declared in this scope
error: 'MATH_ERRNO' was not declared in this scope
error: 'MATH_ERREXCEPT' was not declared in this scope

I have looked for these symbols in the normal include headers but I don't see them.  Any help is greatly appreciated. I must note that  math_errhandling, MATH_ERRNO,  MATH_ERREXCEPT and the pragma  STDC FENV_ACCESS are part of the c++(2011) standard.

#include <cmath>
#include <fenv>
#include <cerrno>


#pragma STDC FENV_ACCESS ON
if (math_errhandling & MATH_ERREXCEPT) {
feclearexcept(FE_ALL_EXCEPT);
}
errno = 0;
result = pow(x, y);

if ((math_errhandling & MATH_ERRNO) && errno != 0) {
  /* Handle range error */
}
else if ((math_errhandling & MATH_ERREXCEPT) &&
           fetestexcept(FE_INVALID | FE_DIVBYZERO |
                        FE_OVERFLOW | FE_UNDERFLOW) != 0) {
  /* Handle range error */
}
}
/ Use result... /
}
0
I'd like to be able to PING from my MS C++ program.    I'd rather not do it by a command line and then parse the string response, because I think different language PCs emit a different text response, and I just need this to work on all PCs.   Ideally I want to call

int ms = Ping("192.168.1.20");

in my C++ program, and "ms" is the trip time that ping normally reports.   Or maybe I need a variant where I can set the timeout duration in ms, like:

int ms = Ping("192.168.1.20", 500);

I happen to know that this is pretty easily done in C# but I can't find how to do it from C++.
0
Hi,
Is there a C/C++ equivalent function for rounding half-even? I need identical function to Java's BigDecimal.setScale(int scale, BigDecimal.ROUND_HALF_EVEN);
So 20.225 = 20.22
20.235 = 20.24
Thanks.
0
what is the reason for getting error while the same code for class name starting with caps compiling and running well.
#include <iostream>
using namespace std;
template<typename t>
class max{t n1;
t n2;
public:
      max(t a,t b){n1=a;n2=b;
      }
      t maximum(){return (n1>n2)?n1:n2;
      }
};
int main(){max<int> obj(5,8);
obj.maximum();
return 0;
}
error: In function 'int main()':
      [Note] candidates are: template<class t> class max

#include <iostream>
using namespace std;
template<typename t>
class Max{t n1;
t n2;
public:
      Max(t a,t b){n1=a;n2=b;
      }
      t maximum(){return (n1>n2)?n1:n2;
      }
};
int main(){Max<int> obj(5,8);
obj.maximum();
return 0;
}
output:8
0
Hi I am seeing "address 0x1 out of bounds segmentation fault" while  accessing the iterater address
typedef eastl::map< EA::TDF::TdfString, eastl::vector<Blaze::Stats::StatDescSummary*> > StatsListByCategoryMap;
```StatsListByCategoryMap::const_iterator itr = mStatsListByCategoryMap.begin();
    for (; itr != mStatsListByCategoryMap.end(); itr++)
    {
        eastl::vector<StatDescSummary*>::const_iterator itrStatDesc = itr->second.begin();
        for (; itrStatDesc != itr->second.end(); itrStatDesc++)
        {

            if ((*itrStatDesc) && (*itrStatDesc)->getName())
            {
                                          statsMap[(*itrStatDesc)->getName()] = getRandomVal(100);
            }```

Acessing value *itrStatDesc->getName()
0
why the below code is not working in dev cpp compiler?
#include<iostream>
#include<typeinfo>
using namespace std;
class A{public:
      virtual void f(){
      }
};
class B{};
class C{
};
bool check(A* ptr){B *der;
if(der=dynamic_cast<B* >()ptr)
return true;
else return false;
}
int main(){B* d1=new B;
C* d2=new C;
if(check(d1))cout<<"ok";
else
cout<<"not ok";
return 0;      
}//error: cannot convert 'B*' to 'A*' for argument '1' to 'bool check(A*)'
0
I need to read any type of file
encode it using huffman
decode it using huffman
MD5  Sum should match after decoding

only condition is the encoded file should have less size than original file
can anyone help me with that it can be done in java or C++
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.