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 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
Dual pipe producer/consumer blocked by read.

The issue is in the producer:
        read(consumer_to_producer[0], &cnt, sizeof(cnt));
        read(consumer_to_producer[0], shared_arr, sizeof(shared_arr));

Open in new window

prevents the producer from working because the consumer has yet to write anything, how can I avoid this?


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

int shared_arr[SIZE];
int cnt = 0, in = 0, out = 0;
int consumer_to_producer[2], producer_to_consumer[2];

void consumer();
void producer();

int main() {
    pipe(consumer_to_producer); // consumer to producer
    pipe(producer_to_consumer); // producer to consumer

    if (fork() == 0) {
        /* child process */
        consumer();
    } else {
        /* parent process */
        producer();
        sleep(3);
    }

    exit(0);
}

void consumer() {
    /* consumer process */
    close(producer_to_consumer[1]); // Close write end, we don't need it
    close(consumer_to_producer[0]); // This fcn doesn't need read end
    while (1) { 
        /* if buffer is full, consume it */
        // read in cnt from producer so we can check if it's full
        read(producer_to_consumer[0], &cnt, sizeof(cnt));

        if (cnt == SIZE) { /* If full, consume */
            read(producer_to_consumer[0], shared_arr, sizeof(shared_arr));
            printf("I am consuming\t%d\t%d\n", shared_arr[in], out);
            out = (out + 1) % SIZE;
            cnt--;
        } 

        

Open in new window

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
Hi,
I'm trying to create a map of <string, pointer to a function> where the functions signature may vary (all of them return int, bu may take arguments of different types). All the functions are template functions.
I'm using a multimap of <string, std::function<int(boost::any*)>*>, but when I'm trying to instantiate a function with type boost::any i'm getting a compilation error.

I wonder if there is any neat solution or bypass.
Thanks.
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
Being forced to deal with 64-bit OS..one of my critical apps is 16-bit.  This must be launched from a process that will be running on the 64-bit side - the process is a program written in C++.

Assuming I can install Windows Virtual PC on the 64-bit OS, and the critical 16-bit program will indeed run (with Windows Virtual PC in XP mode):

How would I modify my C++ program to launch the 16-bit program (on the virtual PC), from my process on the 64-bit side?

I use CreateProcess() today.
0
I need open ShellExecute in thread...



void H_Scan(){
      again2:
        ShellExecute(NULL, "runas", "hosts\\scanner.exe", NULL, NULL, SW_SHOWDEFAULT);
        Sleep(800);
      goto again2;
}

HANDLE EUR;

void MyProtect(){
      EUR = CreateThread(NULL,NULL,LPTHREAD_START_ROUTINE(H_Scan),NULL,0,0);
      }



It does not work, Shellexecute does not work, but any other code works in that case.

I need to run the program every X time so this sleep ... can anyone help me to improve?
0
hello

I am  trying to compile a 2010 project .soln on visual studio 2017 . It had several references to other *2008.vcxproj

I have renamed the  *2008.vcxproj , *2008.vcproj to *2010.vcproj so that i could get it to work and then retarget the whole thing t o 2017.

However, it didn't work. And now, i get complaints about

Collection was modified. enumeration operation may not execute. <------ What does this error mean anyway?

whenever i attempt to retarget solution.

What (and where) needs to be done to manually modify the xml vcxproj so that i can modify everything once and have it target to 2017 successfully?

thanks
0
I consume a web services client.
I have a certificate with password. I can retreive the certificate from my store and i can use it in InternetSetOption.
But I don't know how to send the password with the certicate.

Thanks for your hep.

Here is an example:

      LPWSTR pswzFirstCert = L"xxxxx";// Subject of the first certificate.
      LPWSTR pPassword = L"yyyyyy";// Spassword
      HCERTSTORE hSystemStore; // The system store handle
      PCCERT_CONTEXT pDesiredCert = NULL;

      hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER,L"MY");
      if(hSystemStore == NULL)
      {
            ShowMessage("Not Opened the MY system store.");
            return;
      }

// Get a certificate that has the string "Full Test Cert" in its subject.
      if(pDesiredCert)
            CertFreeCertificateContext(pDesiredCert);

      pDesiredCert=CertFindCertificateInStore(hSystemStore, MY_ENCODING_TYPE, 0, CERT_FIND_SUBJECT_STR, pswzFirstCert, NULL);
      if(pDesiredCert == NULL)
      {
            ShowMessage("The certificate was not found.");
            return;
      }

      if(hSystemStore)
            CertCloseStore(hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG);

      if( InternetSetOption (Data, INTERNET_OPTION_CLIENT_CERT_CONTEXT, (LPVOID)pDesiredCert, sizeof (CERT_CONTEXT) ) == FALSE )
            ShowMessage("InternetSetOption failed with error.");

      if( InternetSetOption (Data, INTERNET_OPTION_PASSWORD, (LPVOID)pPassword, sizeof (pPassword) ) == FALSE )
            ShowMessage("InternetSetOption failed with error.");

      if(pDesiredCert)
            …
0
I am writing a software removal program, and want to uninstall a context menu driver. Just unregistering the driver while Windows File Explorer is open causes a Windows error "Program has stopped working" when trying to unregister the dll. Closing file explorer first and then running the program works fine.

Here is the unregister code I am using now:

HINSTANCE hLib = LoadLibraryW(szDllPath);

    if (hLib == NULL)
    {
		DWORD dwErrorCode = GetLastError();
		szError.Format(_T("\nWindows could not load library %s due to %s"),szDllName,getLastWinError(dwErrorCode));
		return false;            
    }

    typedef HRESULT (CALLBACK *HCRET)(void);
    HCRET lpfnDllRegisterServer;

    // Find the entry point
    lpfnDllRegisterServer = (HCRET)GetProcAddress(hLib, "DllUnregisterServer");



    if (lpfnDllRegisterServer == NULL)
    {
		szError = NEWLINE;
		szError = ERR_PROCEDURE_ADDRESS;
		return false;            
    }

    // Call the function by function pointer..
    if (FAILED((*lpfnDllRegisterServer)()))            
    {   
		szError.Format(_T("\nWindows could not unregister context menu driver %s!"),szDllName);
		return false;            
    }

    FreeLibrary(hLib);

Open in new window


What is the best way to go about this to avoid this Windows error?
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
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
I need to deploy c++ redistributable 2013 to about 400 computers on a domain network.  I have downloaded the executables and found the .msi files, there are two of them, and the .cab files that go with each .msi.  I have also created a transform file to add the ADDEPLOY property with it set to one.  I put the cab file in the same folder as the .msi for each of them.  I then created a gpo to install both msi's.  It does not appear to be working but I don't get any messages in gpresults.  Not sure if I am missing something.
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.