C++Sponsored by Flatiron School

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

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
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
Hello,
I am trying to run this simple program in visual studio 2017 community edition and I am getting compilation error
Error      C2059      syntax error: '...'      

where am I going wrong here? Please help

#include "stdafx.h"
#include<iostream>

using namespace std;

template <typename ...Args>
void Printer(Args&&... args)
{
	(cout << ... << args) << endl;
}

int main()
{	
	Printer(1, 2, 3, "abc");
    return 0;
}

Open in new window

0
I would like to know how to fix the commented out code at line 20 so that I can std::copy a vector into a set. (I know I can copy the vector into the set using for-loops.) If this cannot be done, could you please explain why I am getting the error shown below.
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

int main()
{
   cout << "Hello World" << endl; 
   vector<int> v1(9,12), v1a(9,14);
   v1[0] = 99;
   
   copy(v1.begin(), v1.end(), v1a.begin() ); // no problem copy vector to vector
   cout << v1[0]  << " " << v1[1] << endl;
   cout << v1a[0] << " " << v1a[1] << " " << *(v1.begin()) << endl;

   set<int> s2( v1.begin(), v1.end() );
   set<int> s3;
//   copy( v1.begin(), v1.end(), s3.begin() );  // Compile error. How to std::copy from vector to std::set?
   
   set<int>::iterator sit = s2.begin(); // can increment this set iterator to get good results
   cout << s2.size() << " " << v1.size() <<  "   "  << *sit << "  " << *++sit << "  " << endl;
   
   return 0;
}

Open in new window


/* OUTPUT
Hello World
99 12
99 12 99
2 9   12  99  
*/

Open in new window


Even if you can fix the above error, would you mind interpreting the below error.
$g++ -o main *.cpp
In file included from /usr/include/c++/7/bits/char_traits.h:39:0,
                 from /usr/include/c++/7/ios:40,
                 from /usr/include/c++/7/ostream:38,
                 from /usr/include/c++/7/iostream:39,
                 from main.cpp:1:

Open in new window

0
hi friends ,i am a beginner in c++ and i have some questions and i will be thankful if you help me to find its answers
1-a)a dynamic local variable has been declared in a function (method)
as below:
Work * p = new Work (p);

at the end of the function will this variable be released and erased (without making a call to its destroyer)?
b)if so: and if we call the destructor what will change?
------
2-And if we declare in its place a static variable:
Work p;

at the end of the function will this variable be released and erased?

-------------------------------------------------- -------------------------------------------------- ------------------
3-why do we prefer to work with a dynamic variable (and not a static variable) as a local variable?
0
Dear all,

I have an open code of MFC made in 2002. Could someone please tell me approximately which is the version of this script?

I imagine it is Microsoft C or Microsoft C++, but which version if was compiled in 2002?

Thanks

mfc.jpg
0

C++Sponsored by Flatiron School

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.