Improve company productivity with a Business Account.Sign Up

x

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 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
Free Tool: ZipGrep
LVL 12
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

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
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
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
Get expert help—faster!
LVL 12
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

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
I'm learning Corba with OmniORB and try to compile simple example program but it doesn't work. Unfortunately is really hard to find some information how to do it.

What I do looks like:
I made simple interface file in idl directory

interface IssueAlert {
  string sendAlert(in string alert);
};

Open in new window

Compile it using omniidl -bcxx -Wbexamples echo.idl
I get result files and using examples made that code as a server app.

#include "idl/echo.hh"
#include <iostream>
using namespace std;


class IssueAlert_i : public POA_IssueAlert {
  public:
    IssueAlert_i();
    virtual ~IssueAlert_i();
    char* sendAlert(const char* alert);
};

IssueAlert_i::IssueAlert_i(){}
IssueAlert_i::~IssueAlert_i(){}

char* IssueAlert_i::sendAlert(const char* alert){
  cout << "Upcall: " << alert << endl;
  return CORBA::string_dup(alert);
}

//////////////////////////////////////////////////////////////////////

int main(int argc, char** argv){
   try {
     CORBA::ORB_var          orb = CORBA::ORB_init(argc, argv);
     CORBA::Object_var       obj = orb->resolve_initial_references("RootPOA");
     PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);

     PortableServer::Servant_var<IssueAlert_i> issue = new 
     IssueAlert_i();

     PortableServer::ObjectId_var issue_id = poa->activate_object(issue);

      // Obtain a reference to the object, and print it out as a
      // stringified IOR.
      obj = issue->_this();
      CORBA::String_var 

Open in new window

0
As per c++ primer book the description of writing stream opearator(<<) is-

std::cout << "Enter two numbers:" << std::endl;

 The << operator takes two operands: The left-hand operand must be an ostream object; the right-hand operand is a value to print. The operator writes the given value on the given ostream. The result of the output operator is its left-hand operand. That is, the result is the ostream on which we wrote the given value. Our output statement uses the << operator twice. Because the operator returns its left-hand operand, the result of the first operator becomes the left-hand operand of the second. As a result, we can chain together output requests.

I can't understand the above description. That is why we need two operators because one << operator is enough to print the values?
0
I am new to C++. I can't get the difference between `iostream` library and `using namespace std;` because `iostream` library are two types named `istream` and `ostream`, which represent `input and output streams`, respectively. And `namespace std` is the `standard namespace`.` cout`, `cin` and a lot of other things are defined in it. (This means that one way to call them is by using `std::cout` and `std::cin`.)

So my question is, what is the need of defining both `iostream` and `using namespace std;` in a program?
0
Hi Experts,

i am currently trying to compile an existing C++ project with Framemaker Development kit 2017. The earlier project was compiled with Framemaker dev kit 2015. However, whenever I am trying to compile the project I receive the following error. I think its a linking error but I tried almost all possible combinations to compile.

I am using Visual Studio 2013 ultimate since the FDK2017 lib need minimum VS2013 to compile.

Error	86	error LNK1120: 59 unresolved externals	C:\test\Project\Release 2015\Launcher.exe	Launcher
Error	28	error LNK2001: unresolved external symbol "__declspec(dllimport) __int64 const std::_BADOFF" (__imp_?_BADOFF@std@@3_JB)	C:\test\Project\Launcher\Launcher.obj	Launcher
Error	36	error LNK2001: unresolved external symbol "__declspec(dllimport) bool __cdecl std::uncaught_exception(void)" (__imp_?uncaught_exception@std@@YA_NXZ)	C:\test\Project\Launcher\Launcher.obj	Launcher
Error	22	error LNK2001: unresolved external symbol "__declspec(dllimport) char const * __cdecl std::_Syserror_map(int)" (__imp_?_Syserror_map@std@@YAPBDH@Z)	C:\test\Project\Launcher\struct.lib(strUtils.obj)	Launcher
Error	23	error LNK2001: unresolved external symbol "__declspec(dllimport) char const * __cdecl std::_Syserror_map(int)" (__imp_?_Syserror_map@std@@YAPBDH@Z)	C:\test\Project\Launcher\fdk.lib(pathmap.obj)	Launcher
Error	24	error LNK2001: unresolved external symbol "__declspec(dllimport) char const * __cdecl std::_Syserror_map(int)" 

Open in new window

0
Hello dear experts
I have a editbox in mfc dialog based application.
user must enter a long number in editbox (like 123456789123456789) and the application must make some calculations on it and then show it to user on another editbox.
how can I convert CString to long int and after calculation again convert long int to CStirng to pass to next editbox.
thank you
0
I have a dll written in Delphi that I need to call from a c++ program. My dll works when called from Delphi, both when using static and dynamic loading. However, in c++, LoadLibrary returns a null pointer. In both cases, test.dll is located in the same dir as the test program. I am a c++ beginner - any help is appreciated.

The dll:
library test;

uses
  System.SysUtils,
  System.Classes;

{$R *.res}
 function AddIntegers(_a, _b: integer): integer; stdcall;
begin
  Result := _a + _b;
end;

exports
  AddIntegers;

begin
end.

Open in new window


The Delphi test program - this return the line "3 + 4 is 7", as expected:
program SimpleDLLTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, Winapi.Windows;

type
  TAddIntegersFunc = function (_a, _b: integer): integer; stdcall;
var
  DllHandle : HMODULE;
  AddIntegersFunc : TAddIntegersFunc;
  TestInt         : integer;
begin
  try
    DllHandle := LoadLibrary(pWideChar('test.dll'));
    if DllHandle = 0 then begin
      Writeln('Error loading dll');
    end else begin
      @AddIntegersFunc := GetProcAddress(DllHandle, 'AddIntegers');
      if assigned(AddIntegersFunc) then begin
        TestInt := AddIntegersFunc(3,4);
        Writeln('3 + 4 is ' + IntToStr(TestInt));
      end else begin
        Writeln('Function not found');
      end;
    end;
    Write('Press Enter'); ReadLn;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Open in new window


The c++ test program:
#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
	HINSTANCE hGetProcIDDLL = LoadLibrary("test.dll");

	if (!hGetProcIDDLL)
	{
		cout<<"Could not load library!\n";
		cin.get();
	}
	else
	{
		cout<<"Library loaded!\n";
		cin.get();
	}

	return 0;
}

Open in new window


I did not write any function call in c++, since I have not yet even managed to load the library - I just get "Could not load library".
0
I am creating an executable C++ program that will automatically read the size of a file and if it stops changing, it will copy and move that file to a different folder.  I am relatively new at programming so am not sure how to pursue this program.  The file is a binary (.hst) file.  Thank you in advance.

Also I am using Microsoft Visual Studio 2010 and with it I am using C++ Win32 console development platform.
0
How do you Switch Views within the same Child Frame?  C++ VS2018 15.5.6  I am using the MFC Doc/View Architecture.  I can create new 7 document, as programed.  I have seen several different code examples for do it within the Main Frame, however not within the Child Frame class.  I have created several different CView based classes.  I have added the #include(s) for them in the App.h file header, and this header is included in the ChildFm.cpp file.  It shows up OK as far as Intellisense is concerned.  
// ChildFrm.cpp : implementation of the CChildFrame class
//
#include "stdafx.h"
#include "TCPG.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CChildFrame
IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWndEx)
BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWndEx)
      ON_COMMAND(ID_VIEW_PLAYERVIEW, &CChildFrame::OnViewPlayerview)
      ON_COMMAND(ID_VIEW_QUESTIONVIEW, &CChildFrame::OnViewQuestionview)
      ON_COMMAND(ID_VIEW_LAYOUTVIEW, &CChildFrame::OnViewLayoutview)
      ON_COMMAND(ID_VIEW_YOURREADING, &CChildFrame::OnViewYourreading)
END_MESSAGE_MAP()
These are the function declarations for switching the views.  The empty bodies are in the .cpp file.
And all of it compiles OK at this point.  Each view class is filled with all of the necessaries for that class, and works with the CDocument class.
Yet ...  when I add
// ChildFrm.h : interface of the CChildFrame class
//
#pragma once

class CChildFrame : public CMDIChildWndEx
{
      DECLARE_DYNCREATE(CChildFrame)
public:
      …
0
Free Tool: IP Lookup
LVL 12
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hi
I'm trying to Create a Simple Frame window using CFrameWnd Class.  in the OnCreate() function I'm Writing  code to Create Button using CButton:: Create() function but in that function
it taking parent window handle ...how do I find the handle of the Frame window..please help me.

CButton myBtn;
      afx_msg int OnCreate(LPCREATESTRUCT lp)
      {
            //MessageBox("hello","hi",1);
            
            myBtn.Create("Click me",WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,CRect(10,10,20,30),CFrameWnd::GetActiveView(),1);
            return 0;
      }
thank you
0
Realword: a word that only has letters in it.

Censor Mode: causes the program to only print a word if it is a realword. When in censor mode, any whitespace after the realword is also printed. If a word is not a realword, then it is not printed, nor is any of the whitespace after it.

I am able to check and get rid of the words that digits or punctuations but am not able to take care of the spaces and the newline characters. Below is my code and attached is the input and the expected output and the output that my program is generating.

#include <iostream>
#include <string.h>
#include <fstream>
#include <stdio.h>
#include <cctype>
#include <sstream>
using namespace std;
bool foundRealWord=false;
namespace flagModes{
	string squish (string line){
		string orig = line;
		int len = line.length();
		string squishedString;
		for(int i=0; i<len; i++){
			if(squishedString.length()==0){
				if(isspace(orig[i])){
					continue;
				}
				else{
					squishedString+=orig[i];

				}
			}
			else {
				if(isspace(orig[i])){
					continue;
				}
				else if(isalpha(orig[i])){
					if(isspace(orig[i-1])){
						squishedString+=" ";
						squishedString+=orig[i];
					}
					else{
						squishedString+=orig[i];
					}
				}

			}

	}
		return squishedString;
	}
	string censor (string word){
		string origWord=word;
		string censoredWord="";
		int len = origWord.length();
		if(len==0){
			//censoredWord += "\n";
			return censoredWord;
		}
		else{
			for(int i = 0; i<len; i++){
		

Open in new window

0
Hello!!!!


How to convert this;

std::string response;
char time[13];

...

response.copy(time, 13,223);
time[13] = '\0';
printf("%s\n" ,time); // this print value:1517691086218

       ????   //how to convert char time[13] to int ?

       if (time == 1517691086218){
	printf("OK %d\n" ,time);
	} else {
	printf("NOT\n %d\n" ,time);
	}

Open in new window



How to convert;

char time[13] = '1517691086218'

to

int value = 1517691086218

?

Thanks...
0
Hi, I've always used CURL, but I was forced to use sockets this time for some reason. This is my code;

#include "stdafx.h"
#include <winsock2.h>
#include <string>
#include <iostream>
using namespace std;

void HTTPReq(
    const char* verb,
    const char* hostname,
    int port,
    const char* resource,
    const char* opt_urlencoded,
    string& response)
{
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
    {
        cout << "WSAStartup failed.\n";
        exit(1);
    }

    SOCKET Socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

    struct hostent *host;
    host = gethostbyname(hostname);

    SOCKADDR_IN SockAddr;
    SockAddr.sin_port=htons(port);
    SockAddr.sin_family=AF_INET;
    SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

    if (connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
    {
        exit(1);
    }

    // Build request
    string req = verb; // GET | POST
    req.append(" ");
    // Note, on GET, 'resource' must contain the encoded parameters, if any:
    req.append(resource);
    req.append(" HTTP/1.1\r\n");

    req.append("Host: ");
    req.append(hostname);
    req.append(":");
    req.append(to_string(static_cast<long long>(port)));
    req.append("\r\n");

    if (strcmp(verb, "POST") == 0)
    {
        req.append("Cache-Control: no-cache\r\n");
        req.append("Content-length: ");
        req.append(to_string(static_cast<long long>(strlen(opt_urlencoded))));
        

Open in new window

0
I have an application developed by a small-ish company. The application terminates roughly every day, I analyzed the crash dump and I see heap memory corruption was detected in myapplication.exe.. Vendor is out of ideas. Server is 2012R2, any suggestions on where I could start, thanks.
0
Hello All,
I am trying a small sample Template code. I am getting linker error. I have declared and defined all the methods.
If I move the code from cpp to header then i dont see any linker error. Keeping them separate in header and CPP file is causing the issue. I am not sure what I am missing. I have attached the code for reference.
Please help me.
CodeFiles.zip
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.