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

Need some help to C++ if Statement.
I will not catch the -0.01 to -0.99 with this if statement.
The crText will be blue and not red
prozent= double variable
                  
                   if(prozent<0)
                   {
                          crText = RGB(255,0,0);      //red
                     }
                   else
                   {
                         crText = RGB(0,0,255);      //blue
                     }
Please let me know how I can fix this simple statement.
Thank you.
Best regards,
Thomas
0
OWASP: Avoiding Hacker Tricks
LVL 19
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Hello, I'm rather new to C++.  I've been viewing a lot of video training courses to help me learn the syntax, but once I pick that up, I'm off to writing a specific program that I'd like to develop.

I would like to ask whether anyone here knows of any books, PDF, articles or reference material that would help me understand how to use C++ for FileInfo and Disk.IO programming.

I need to develop code that can analyze a hard drive and provide me technical information about that hard drive and about the O/S (i.e. number of sectors, block size, file dates, etc.).

I would need this material to be somewhat specific to the topics I specified above. I'm not looking for a C++ primer for simple coding tasks, I'm looking for something specific for FileInfo and Disk.IO programming.

Thank you for your help,
Fulano
0
Hi, I haven't coded much in C++, but have the need to do so for a specific project.  I was wondering if there is a difference (in results) between native C++ using a Text Editor and a GCC compiler and the Microsoft C++.NET development environment?

I need to code a few simple programs that look at a computer hard drive and identify specific traits of that hard drive, like how many sectors it has, its size, etc. (Yes, I know I can do that commercially, but I need to develop the custom tools for a bigger project).

So, which development tool should I use... native C++ with a GCC compiler, or could I use the MS C++.NET version, which is a lot simpler to use...and still get the same results?

Thank you,
Fulano
0
I have a beginner question about c++. How I can avoid that the for loops run when FirstSession and LastSession both are 0.

   
 for (int32 i = mi.nFirstSession; i <= mi.nLastSession; i++)
{

Open in new window


Currently it will run if FirstSession and LastSession are 0.
0
In my app I use an mdiArea as central widget. Inside this I create different Childs.

Like:
    MdiChildDiskInfo *child = new MdiChildDiskInfo(this,strDriveName);
    if(child){
        mdiArea->addSubWindow(child);
        child->showMaximized();
    }

Open in new window


The MdiChildDiskInfo is a
class MdiChildDiskInfo : public MdiChildBase
that is basing on
class MdiChildBase : public QMainWindow

Open in new window


The MdiChildDiskInfo is created with
MdiChildDiskInfo::MdiChildDiskInfo(QWidget* parent, const QString &device)
    :strBurnDrive(device){
      setAttribute(Qt::WA_DeleteOnClose);

      this->close();

}

Open in new window


I tried to stop creating the MdiChildDiskInfo with this->close() while the MdiChildDiskInfo is created. The close event is fired.
But always an empty QSubWindow is created. Means child has always an object.

I expect that the child is null when I add this->close() to the constructor. Special in case of Qt::WA_DeleteOnClose. But child is always an object. It looks that the MdiChildDiskInfo is always create also if I say close it.

Finally I want that
MdiChildDiskInfo *child = new MdiChildDiskInfo(this,strDriveName);
will return null to child.
0
Hello;

I have a c++ program which launch a Delphi DLL where there are informations i need in C++.

So I need to return data from Delphi to C++.

I make some tries, and the last succefull try was to pass a c++ pointer to function and use the function in the delphi side;

Until Now, everything is OK;

the problem occurs when i try to send string from Delphi to C++; I receive non comprehensible string; ( chinese letters + arabic letters + mathmatical symbols ).

after several tries; I noticed that in Delphi, the problem occurs if there is a UnicodeString or String in the program even if it is not in the string sent to C++.

If I have only PWideChar in the program, that works; if there is String or UnicodeString, AnsiString ..., (even if it is not concatenated to PWideChar), the received string is unreadable.

I hope find a solution for this problem. I will put some code in commentaires.
0
My application (C++, WxWidgets, Ubuntu) have to play different mp3 files depending on user actions. At the moment, I use vlc library and I always call a new function to reproduce the audio file, but this requires too much code and I think it's not so professional. Since I do not want to stop the flow of the application while the mp3 is playing, I use threads.

I tried to write a class for the mp3, but I think it is not correct since I get this error:

  /home/isola/Documents/Isola02/secondpanel.cpp:68:102: error: invalid use of void expression
  pthread_create(&thread, NULL, mp3->play_mp3("/home/user/Project/audio/scegli-rifiuto.mp3"), NULL);

Open in new window


This is the code of my class:

rePlay.cpp
#include "rePlay.h"
#include <vlc/vlc.h>

rePlay::rePlay()
{
    //ctor
}

rePlay::~rePlay()
{
    //dtor
}

void rePlay::play_mp3(const char* path){
  // load the vlc engine
    inst = libvlc_new(0, NULL);
    printf("apro il file %d\n", inst);
    // create a new item
    m = libvlc_media_new_path(inst, path);
    // create a media play playing environment
    mp = libvlc_media_player_new_from_media(m);
    // no need to keep the media now
    libvlc_media_release(m);
    // play the media_player
    libvlc_media_player_play(mp);
    printf("Done.\n");
}

void rePlay::stop_mp3(){
  // stop playing
    libvlc_media_player_stop(mp);
    // free the media_player
    libvlc_media_player_release(mp);
    libvlc_release(inst);
}

Open in new window

and the header rePlay.h
#ifndef REPLAY_H
#define REPLAY_H
#include <vlc/vlc.h>

class rePlay
{
    public:
        rePlay();
        virtual ~rePlay();
        void play_mp3(const char*);
        void stop_mp3();
    protected:
        libvlc_instance_t *inst;
        libvlc_media_player_t *mp;
        libvlc_media_t *m;
    private:
};

#endif // REPLAY_H

Open in new window

My idea is to call:

pthread_t thread;
rePlay *mp3;
pthread_create(&thread, NULL, mp3->play_mp3("/home/user/Project/audio/scegli-rifiuto.mp3"), NULL);

Open in new window


by passing the path of the file each time I want to reproduce a mp3 and then to call:

pthread_create(&thread, NULL, mp3->stop_mp3, NULL);

Open in new window


when I want to stop it.

At the moment, I get this error from the compiler regarding the pthread_create, but I think there should be other problems since I do not know if the play_mp3() and stop_mp3() could work.

Can you help me, please?
0
I'm using Ubuntu and I have a C++ application which uses WxWidgets and sends a string over TCP several times. It works pretty fine only if the router and the connection are OK, otherwise it gets stuck and I need to manually quit the application.
I would like to send the data without blocking the application flow in case of errors.

I call the function in this way:

   
 SendCommand ptr;
    if ( ptr.sendcommand(16,16,1) ){
    printf("Porta Aperta\n");
    } else {
    printf("Errore di comunicazione - porta non aperta\n");
    }

Open in new window


and this is the function:

int SendCommand::sendcommand(int relay_on, int relay_off, int stop){
    printf("eseguo la funzione nella classe\n");

    std::array<uint8_t, 8> command1;
    std::array<uint8_t, 8> command2;

    switch(relay_on){

    case 16: command1 = {0x58, 0x01, 0x12, 0x00, 0x00, 0x00, 0x10, 0x7B}; // switch on the relay 16
    break;

    }

    switch(relay_off){

    case 16: command2 = {0x58, 0x01, 0x11, 0x00, 0x00, 0x00, 0x10, 0x7A}; // switch off the relay 16
    break;

    }

    int sockfd, n;
    struct sockaddr_in servaddr;

    std::string serveraddr = "192.168.1.4";

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if ( sockfd < 0 )
    {
        cerr << "Error creating socket! " << strerror(errno) << endl;
        return -1;

    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(serveraddr.c_str());
    servaddr.sin_port

Open in new window

0
I am trying to add icon to a context menu in a MFC app.

this code adds a textual menu item, but how do I add the icon to it?
CMenu l_menu;
l_menu.CreatePopupMenu();
l_menu.AppendMenu(MF_STRING, ID_REPORT_COLUMN_NEW, _T("some string"));

Open in new window

Thank you
Vaclav
0
Im trying to make a small battery tester.

It is charging up battery fine up to 2kv while reading analog values, then goes into discharging loop and dies there.  I need help with the second loop.

Can you please help?

I want to charge and discharge while reading analog values over and over again in endless loop.

void loop(){
  
  // read the raw data coming in on analog pin 0:
  int val = analogRead(analogPin);  // read the input pin
  // Convert the raw data value (0 - 1023) to voltage (0.0V - 5.0V):
  float voltage = val * (5.0 / 1024.0); 
  //convert to actual voltage
  int volts = voltage * 10000; 

  
  //if the voltage is less than 2,000v keep charging
  if (voltage < 0.19){
  lcd.setCursor(1,1);
  lcd.print("Charging     ");
  digitalWrite(chargePin, HIGH); 
  
  //print to lcd
  lcd.setCursor(1,0);  
  lcd.print("Volts: ");
  lcd.print(volts); 
  lcd.print("     ");
  delay(100); 
  }

  else{  
    //we reached 2000v, discharge untill fully discharged
    while (voltage > 0.01){  
    lcd.setCursor(1,1);
    lcd.print("Discharging    ");
    digitalWrite(chargePin, LOW);
    
    //print to lcd
    lcd.setCursor(1,0);  
    lcd.print("Volts: ");
    lcd.print(volts); 
    lcd.print("     ");
    delay(100); 
    }
  }

  
}

Open in new window

0
Exploring SharePoint 2016
LVL 19
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.

Need help to convert below C++ code to C#. Thanks for the help.

In C++:
double dValue = 14 / 1000;
ostringstream oss;
oss.precision(10);
oss<<fixed<<dValue;
string sValue = oss.str();
1
Tried to use VC++ 2008 command line utility cl to compile the code that contains an array with variable size. A lot of errors were generated. In Linux all needs to do is to include the option -std=C99 when compiling.  Is there any workaround for it? Can any gurus shed some light to it? Thanks a lot.
0
I have an electronics board which has 16 relays and it works over TCP/IP.
The IP address of the board is 192.168.1.4 and the port is 3000.
I would like to control it with C/C++ under Ubuntu.

There is a list of HEX commands that it is possible to use in order to remotely switch ON and OFF each relay on the board.
This is the list:
"580112000000016C",  // switch on the relay 1

"580111000000016B",  // switch off the relay 1
"580112000000026D", // switch on the relay 2
"580111000000026C", // switch off the relay 2
"580112000000036E", // so on..
"580111000000036D",
"580112000000046F",
"580111000000046E",
"5801120000000570",
"580111000000056F",
"5801120000000671",
"5801110000000670",
"5801120000000772",
"5801110000000771",
"5801120000000873",
"5801110000000872",
"5801120000000974",
"5801110000000973",
"5801120000000A75",
"5801110000000A74",
"5801120000000B76",
"5801110000000B75",
"5801120000000C77",
"5801110000000C76",
"5801120000000D78",
"5801110000000D77",
"5801120000000E79",
"5801110000000E78",
"5801120000000F7A",
"5801110000000F79",
"580112000000107B",
"580111000000107A",
"5801130000FFFF77",
"580113000000007B",
"5801100000000069"

I'm correctly able to switch on and off each relay by sending command line commands under Ubuntu:

echo '580112000000016C' | xxd -r -p | nc 192.168.1.4 3000

Open in new window

The above code correctly turns on the relay.

I would like to do the same with C/C++ code since I want to control the …
1
I'm developing a WxWidgets application under Ubuntu and I'm using CodeBlocks as IDE.

I need to:

  • read the data stored in a magnetic card band
  • check if they are OK
  • parse the string in order to get the code, the name and the surname

I'm using a USB magnetic card reader and I set a TextCtrl as "focused" so it immediately gets the data from the reader automatically.

The format of the string is like this:

%URSMCC84R04E815LURSO  MARCO_ò8038001605011036724_

Open in new window


The control characters are always the same and I need to read everything between % and _.
I need to obtain three strings:
  • the first one containing the first 16 chars
  • the second contains the surname which goes from the 17th till the first space
  • the third string contains the name and goes from the first char after the space till the _

What is the best way to do this in Wxwidgets?
Moreover, since the reader emulates a keyboard, the output string is read a char at a time, so how can I design the parsing code?

This is the code I'm using to read the string.

void ProjectFrame::OntesseraText(wxCommandEvent& event)
{
    wxString stringa_tessera = tessera->GetValue(); // I read the string coming from the USB reader
    TextCtrl2->ChangeValue( stringa_tessera ); // I load the string in the second TextCtrl just for test
}

void ProjectFrame::OnTextCtrl2Text(wxCommandEvent& event)
{
// TextCtrl used to display the parsed string
}

Open in new window


I see that there is a class wxStringTokenizer, should I use it?
I'm sorry but I'm just a beginner :(

Thank you!
0
I am writing a Win32 Service application using embarcadero XE 10.1 Berlin C++ builder on a 64 bit Windows 7 PC.

I am starting with a trivial project prior to putting "flesh on the bones", but can't get the simple example to work ?
when I run the application with /install as a command line parameter (which usually installs the service app), I get the following error instead.

    Exception EOSError in module KERNELBASE.dll at 0000C5AF.
    System Error. code 5
Access is denied.


I get this error regardless of whether or not the Beep function is called.
I have set the StartType to stDisabled so I would expect the service application to be installed but it isn't.
 The code is as follows, any help would be appreciated. I have written service applications before using Borland C++ builder but no Embarcadero XE C++ builder.


C++ file:
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

TTestServiceName *TestServiceName;
//---------------------------------------------------------------------------
__fastcall TTestServiceName::TTestServiceName(TComponent* Owner)
	: TService(Owner)
{
}

void __stdcall ServiceController(unsigned CtrlCode)
{
	TestServiceName->Controller(CtrlCode);
}

TServiceController __fastcall TTestServiceName::GetServiceController(void)
{
	return (TServiceController) ServiceController;
}

Open in new window

0
Hi, I am trying to see the actual address that a C/C++ pointer points to.  I can easily see the data that it points to but I'm trying to see the actual address of those data, i.e., the contents of the pointer itself.

I am using cout for the attempted display of this which will be an address in hex (along with other data that displays just fine in my cout statement).

The environment is VS2015.

Any help will be appreciated.
0
I am trying to catch an exception that is generated when a TCP client connection is attempted when the connection is already connected. The code that I am using us shown below.
All I get is a message on the screen  as also shown below.
How do I suppress this message and catch the exception in my code ?
I a using Embarcadero XE 10.1 berlin C++ Builder with an Indy 10 TCP client component.

void __fastcall TForm1::Button2Click(TObject *Sender)
{
	try
	{
		IdTCPClient1->Connect();
	}
	catch(...)
	{
        Memo1->Lines->Add(u"Failed to connect");
    }
}

Open in new window


Already connected message
0
I am trying to set up a binding on an Indy 10 TIdUDPServer component with Embarcadero XE 10.1 Berlin  C++ builder

I As soon as the Bind() call is made, I get an error message as follows:

"Exception class EIdNotAsocket with message 'socket Error #10038' Socket Operation on non-socket."

How can I set up the binding ?

the following is my code:

	TIdSocketHandle *h;
	udpserver = new TIdUDPServer(NULL);
	udpserver->OnUDPRead = IdUDPServer1UDPRead;
	h = udpserver->Bindings->Add();
	h->Port = 791;
	h->IP   = "127.0.0.1";
	try
	{
		h->Bind();
	}
	catch(...)
	{
	};

Open in new window

0
I am coding a C++ class which has a member function void Start(list<int> lst);

I wish to assign a default  value to the lst parameter but I haven't worked out how to declare and implement this in the declaration of the member function .

How would I declare this with a default list of integers 1,3,5,7 for example ?

class MyClass
{
        public:
        MyClass(){};
       ~MyClass(){};
void Start(list<int> lst = ???);
}

Open in new window

0
Angular Fundamentals
LVL 19
Angular Fundamentals

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

Is there some functionality already available in C++14 to convert a number from decimal representation into binary?

Thanks.
0
I need to generate an XML document based on the result of a database query (ADOQuery).
Is it appropriate to use a TXMLDocument component and if so how would I do this ?
I am writing a VCL application for windows using Embarcadero C++ builder XE 10.1 Berlin
0
I am unable to get any reply from the Getit Package manager in Embarcadero RAD Studio 10.2 or Embarcadero C++ Builder  XE 10.1 Berlin.
Does anyone know when this will be fixed by Embarcadero ?
0
What is the simplest way to the conversion below?
kconn.cpp:35:15: error: non-const lvalue reference to type 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') cannot bind to a value of unrelated type 'const char [4]'
            addRoute("JFK", "ATL", 150);
                     ^~~~~
kconn.cpp:27:31: note: passing argument to parameter 's' here
        void addRoute(std::string &  s,

Open in new window

1
My IDE is visual studio community 2019.  I'm  unable to link GLUT library with my C++ project.  I get following link errors:

link errors
Do I need to specify some windows libraries in "Additional Dependencies" field?


Additional Dependencies
0
I'm using Visual Studio Community 2019.
I found 'OpenGL C++ Tutorial : Getting Started' on youtube.   I get error when I try to link project.  Maybe I'm not specifying 'Additional Dependencies' correctly in my project setting.  Please see attached.

Also, attached is the link error.
Additional_dependencies.PNG
lib_in_proj_folder.PNG
link_error.PNG
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.