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

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
Introducing Cloud Class® training courses
LVL 12
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

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
Cloud Class® Course: C++ 11 Fundamentals
LVL 12
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

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 have to modify a Qt Creator project on Windows 7. The compiler/linker uses Visual Studio 2010 Pro SP1. (The debugger works on VS, but not on Qt.)
I debug by adding print statements. I want to be able to debug using a debugger.

I found this page which also leads to subsequent links.
http://doc.qt.io/qtcreator/creator-debugger-engines.html

The IT department (one person) is overworked, and this debugger task is considered low priority. Furthermore, the admin has no idea how to get the debugger to work. The lead said that if I can come up with a step-by-step written list of things to do, then he would raise the priority of getting the debugger to work. Statements like "add <...> to Qt screen <...>" doesn't help since IT won't know what to do. Need detailed steps.

Maybe someone has already done this and can provide these detailed steps (supported by links so I can review and ask questions, to help clarify the steps - I get one shot to get this to work). General comments and links without the detailed steps probably won't help the IT guy.

A year ago, I think I saw that we needed a version of SDK (maybe SDK 7.1?) to get the Qt Debugger to work. This SDK is not installed on my Windows 7 workstation, but I am told that we are allowed to install it. In general, we have a list of items we are allowed to install, and anything not on the list is not permitted.

My environment:
Windows 7
Qt Creator 2.6.0 based on Qt 4.8.2
Qt Compiler/linker used is hooked to Visual …
0
Cloud Class® Course: Python 3 Fundamentals
LVL 12
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

If I start a task with a cancellation token, and I later set the cancellation token to "Cancel", can I then immediately dispose of the cancellation token, or do I need to wait for the task to get the "Cancel" message first?

It's appearing as if I don't need to wait for the task to get the "Cancel" message. It seems to get it anyway:
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
mytask = Task.Run(async () => await MyEndlessTaskLoop(token), token);

...
// Then later in a button click event:
cts.Cancel();
cts.Dispose();

Open in new window

Do I need to insert a wait between the "Cancel()" and "Dispose()"?
cts.Cancel();

try {
    mytask.Wait();
}
catch (AggregateException e) {
   // Expect e.InnerException to be "OperationCanceledException"
}

cts.Dispose();

Open in new window


Also do I need to insert an await in front of Task.Run(...)?
mytask = await Task.Run(async () => await MyEndlessTaskLoop(token), token);

Open in new window


And, is there a difference between passing the cancellation token as a parameter as opposed to just using it as a captured variable? As in:
private async Task MyEndlessTaskLoop()
{
    while(True)
    {
        ...
        this.token.ThrowIfCancellationRequested;
    }
}

Open in new window

vs.:
private async Task MyEndlessTaskLoop(CancellationToken token)
{
    while(True)
    {
        ...
        token.ThrowIfCancellationRequested;
    }
}

Open in new window

Is one preferred over the other?
0
Visual Studio LINK warning LNK4098
0
I have been using VS 2008, and have installed VS 2015 side by side on the same computer. I have projects compiled in VS 20015 from another computer that compile just fine. But when I open those projects and try to compile them in the new VS 2015 on this computer they will not compile. In fact, even creating the simplest "Hello world" application will not compile.

I get errors on standard VS header files. For example, it throws errors and warnings on Windows.h like:

Warning      C4067      unexpected tokens following preprocessor directive - expected a newline      windows.h            

Error      C2061      syntax error: identifier 'LPCSTR'      
Error      C2061      syntax error: identifier 'BYTE'      

I can't figure out why this is happening. Anyone have an idea?
0
I have a desktop application written Microsoft Visual C++ using Visual Studio 2017.  Its a single-doc MFC application.   Rather large, developed over the past 15+ years.  Now I want to be able to do something different: normally, of course, the application starts up and shows its GUI on the screen.  I want to add a mode (will have the App check for the presence of a certain file at start up) in which it does not pop its GUI up.  Ultimately, I'd like to have the ability to run it either A) with its GUI as usual, or B) as a GUI-less executable, probably in a windows service.  The app contains a socket-based message system that listens for commands and sends responses -- so when it is running in GUI-less mode, it will be another program talking to it over this socket channel in order to have it do useful work.

So, how to do this?   Maybe forget about the windows service idea for now -- just simply how to start my application and have it run without ever popping a GUI?   The structure, due to MFC, with the Doc, the View, the InitInstance code, the MainFrame class -- all that stuff is kind of mysterious to me.  I just used the structure that the MFC wizard gave me (when I first created this App back in Vis Studio version 6!).  Now it seems I may need some understanding of how to launch the system, but without Mainframe and the View popping up, etc.  Some of the Apps actions occur due to "OnTimer" code which might be on a dialog class -- so it seems to me I'd have to rework that…
0
I am a newbie in the data structure, I have read the implementation of stack using a simple array, the algorithm for this implementation is below:-

 Stack Operations using Array

A stack can be implemented using array as follows...

Before implementing actual operations, first follow the below steps to create an empty stack.

Step 1: Include all the header files which are used in the program and define a constant 'SIZE' with specific value.

Step 2: Declare all the functions used in stack implementation.

Step 3: Create a one dimensional array with fixed size (int stack[SIZE])

Step 4: Define a integer variable 'top' and initialize with '-1'. (int top = -1)

Step 5: In main method display menu with list of operations and make suitable function calls to perform operation selected by the user on the stack.

push(value) - Inserting value into the stack

In a stack, push() is a function used to insert an element into the stack. In a stack, the new element is always inserted at top position. Push function takes one integer value as parameter and inserts that value into the stack. We can use the following steps to push an element on to the stack...

Step 1: Check whether stack is FULL. (top == SIZE-1)

Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and terminate the function.

Step 3: If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value (stack[top] = value).

pop() -
0
When building code, I am not seeing my changes.  I've changed a simple Text Header on a page and ran the code and it does not change.
I've cleared my cache, restarted, tried a clean build and am at a loss as to what cold be causing this.

We have tested and this is only happening on React JSX pages.  It doesn't look like Webpack is compiling the changes but rather old code.
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.