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 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
The new generation of project management tools
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

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
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
[Webinar] Improve your customer journey
LVL 12
[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

C++03 using VS 2010. (Assume no boost available.)

I would like to find the missing points in the below diagram using C++03 std lib. The x's represent a set of given points, and the o's are the missing points.

x----o--x----x---o
|    |  |    |   |
o----o--x----o---x
|    |  |    |   |
o----x--x----o---x
|    |  |    |   |
x----o--x----o---o
|    |  |    |   |
x----x--o----o---o
|    |  |    |   |
o----o--x----o---o

Open in new window

I am given a set of points Pi = (Xi, Yi). The coordinates are of type double. If I were to draw a grid (consisting of horizontal and vertical lines) going though every point, I may have some missing points as shown above.

The result should be a std container having the (X, Y) points that are missing.

I suspect that http://www.cplusplus.com/reference/algorithm/set_difference/ or some variation might be useful. So getting the entire list of potential points somehow is probably also useful. Although speed is always a plus, it is not essential.

Any code suggestions?

BTW - there are NOT going to be any tricky points - like a point very far away from the main set of points.
BTW - I've been using axis indices to represent the actual axis coordinate values (but don't worry about that if it complicates the code).

I can probably do this using brute force using a 2D array; so the purpose of this question is to use std lib algorithm functions to simplify the code and hopefully improve performance.
0
from the attachmet i need to print the output as

1.       class.User                                                                  

2.       class.User.mv.UserID                                             (mvè Member Variable)

3.       class.User.mv.UserPassword
0
I want to create a static class that will hold constants.  Then I want to create another class that can get the value of static class constants.

Can anyone provide a code sample?

Thx
0
I have an algorithm, written in MS C++ that I'm going to move to the cloud.  But I don't know a lot about cloud applications.  The plan is that I just work on my algorithmic code, and somebody else who is versed in cloud stuff will hook it up.   It was suggested that I modify my code into "a DLL that you call from within a web page hosted in IIS".   Can someone tell me what I might need to know about this?   Do you think I need to know anything about web or IIS to do this?  If I just format my code as a DLL that could be called by another C++ program (a test harness) - then should I be able to hand off that DLL to somebody else to stitch into the usage by "a web page hosted by IIS" ?  I would want to supply a DLL (not source code) with a published API that others can put "in the cloud".  Wondering if I need to know about web and IIS...
0
If some process takes too long (about 5 seconds) and the GUI can't refresh, Windows add the words "Not Responding" to the title bar of some or all windows.    Its been hard to figure out what is going on, but it seems this notification causes my MFC application to run the "OnSize" handler for the top most window (I suppose the one that got the "Not Responding" text added).  This is very annoying and was causing my App to crash until I wrote special code to try to determine if a given call to OnSize is legitimate or not -- if not I just return.  Now, at least, it doesn't crash -- but something in this process is taking a lot of time -- my App seems to freeze for a while to try to figure this all out, then resumes again.  Hard to figure out what is going on.  Anyone seen this before?
(btw - I know I should not have long processes in the GUI loop and they should be in a separate thread - and going thru my whole app and making sure that is true is one approach I'm working on, but I think this oddity can occur when some other process on the PC is taking a long time)
0
I have coded a Windows 32 VCL application using Embarcadero C++ builder  EX10.1 Berlin and using a winsoft TOBR barcode recognition component.
The application worked.
I now wish to no longer use the Winsoft component in the application so I removed it from the project entirely,including the library and the obr.hpp header file.
The project now compiles but I get a linker error that the file OBR.OBJ cannot be found when the project no loger uses the component as far as I can see.
Where is the linker getting the reference to OBR.OBJ from or how can I get rid of the error ?

The ilink32 command line is as follows :

  c:\program files (x86)\embarcadero\studio\18.0\bin\ilink32.exe -G8 -L.\Win32\Debug;"c:\program files (x86)\embarcadero\studio\18.0\lib\Win32\debug";
  CivicWeldRESTServer;"c:\program files (x86)\embarcadero\studio\18.0\lib\win32\release";"c:\program files 
  (x86)\embarcadero\studio\18.0\lib\win32\release\psdk";C:\Users\Public\Documents\Embarcadero\Studio\18.0\DCP -j.\Win32\Debug;"c:\program files 
  (x86)\embarcadero\studio\18.0\lib\Win32\debug";CivicWeldRESTServer;"c:\program files (x86)\embarcadero\studio\18.0\lib\win32\release";"c:\program 
  files (x86)\embarcadero\studio\18.0\lib\win32\release\psdk";C:\Users\Public\Documents\Embarcadero\Studio\18.0\DCP -l.\Win32\Debug -C -v 
  -GA"C:\Users\roger\AppData\Local\Temp\vfs7F41.tmp"="C:\Users\roger\Documents\Embarcadero\Studio\Projects\FrameStatusWebServerV2\WebModuleUnit1.dfm" 
  

Open in new window

0
I am getting a linker error when compiling an application with Embarcadero C++ Builder XE10.1 .
The application is a 32 bit windows VCL application (Web application). I can usually fix the error by re-booting the PC and running the compiler before any other application but recently this doesn't fix the problem.
The PC is a Dell precision 7710 with an Intel i7 2.7 Ghz processor and has 32 GB of RAM. the operating system is Windows 7 Professional 64 bit.
Looking around on the web, the issue would appear to be a buggy Embarcadero Linker which isn't going to be fixed any time soon.
Is there any solution to this ?

I have added the following option in the C++ Linker Additional options:   -GHtds=0x0F000000 and have also checked the  "clear state before linking" box in the C++ linker advanced options, neither of which actions has had any effect.

Any help appreciated.

Roger
0
Somewhere along the line, about when OOP came along, I was diverted into doing other things.  So, I lack the "cultural refinement" that must have come along with it.
I've written programs in C, C++, VBA, C#, and Fortran (of whatever recent vintage) but, I must admit, quit in starting on C# because there were all those class names that had no meaning for me.  I couldn't even debug an example program as a result!

I think I understand the general concepts - so that's not it.
It's the specifics that are elusive.
I've seen the same thing in VBA but seem to have been able to get things done.  It was sort of like "programming by example" as in "copy & paste".

I've researched it a bit but don't seem to find the answer.  So:
What is the key to understanding the Classes, what they're called and what they do, so that one can be relatively productive?  Does this come by osmosis?
It must be something like a dictionary....
Or, if the proper term is other than "Classes", can you enlighten me a bit please?
0
#include <iostream>
void Triangle::move(float dx, float dy) {
    x+=dx;
    y+=dy;
}
void Triangle::zoom(float scale){
base*=scale;
height*=scale;
}
float Triangle::area(){
return base*height*(1/2);
}

int main () {
float t1, t2;
Triangle tri1, tri2;
tri1.move(12,0);
t1=tri1.area(); t2=tri2.area();
cout << "area: " << t1 << endl;
cout << "area: " << t2 << endl;
tri1.zoom(2.5);
t1=tri1.area();
cout << "area: " << t1 << endl;
}
This is my main cpp

class Triangle{
public:
    void move(float dx, float dy);
    void zoom(float scale);
    float area();
private:
    float x, y;
    float base, height;
};
This is my header file

I am currently practicing inheritance and polymorphism by myself so I picked up with easier one(which I think is drawing geometric shape) but it is quite harder than I thought. Can someone tell me how to change this with inheritance and polymorphism?
The other problem is that I also found this compiler called OpenGL which can literally draw shapes and I found that codeblock has the option for it. I really wanna try it out but I don't know how because it is not drawing anything even though I selected the option for OpenGL as project type.
0
Never miss a deadline with monday.com
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

I am writing a windows Web application using embarcadero XE10.2 Berlin C++ builder;
The application uses a TWebModule and receives a POST web action from a web page being displayed on a remote mobile device.
the mobile device posts a jpeg image which Is received in the following function, st2 is a TMemoryStream.
I am copying the raw content into a TByteDyneArray b so that I can easily inspect it. I load the TMemoryStream with the raw content and then save the memory stream to a file with the extension .jpg.
This file is reported as corrupt or invalid or too long when I try to open it with windows Photo viewer or the like.
how do I extract the image data ?
The size of the raw data as given by  Request->RawContent.Length is
Inspection of the beginning of the raw content  up to encountering a NULL is shown in quotes below.
"------WebKitFormBoundary9lWvgPDQcTZoDcRf\r\nContent-Disposition: form-data; name=\"picture\"; filename=\"15123250544981385201258.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n�￘�£\x02tExif"

void TWebModule1::Action3Post(TWebRequest *Request,TWebResponse *Response)
{
	UnicodeString u,v,uu="";
	TByteDynArray b;
	char buff='a';

	int n,m,w;
	u = Request->ContentType;
	n = Request->RawContent.Length;
	m = Request->Files->Count;
	b = Request->RawContent;
	st2->Clear();
	b.set_length(n);
	st2->WriteData(Request->RawContent,Request->RawContent.Length);
    st2->Position = soBeginning;

//	Form1->Memo1->Lines =  Request->ContentFields;
	for(;;)
	{
		

Open in new window

0
Hello all,

Using Borland C++ 4.52 on a Windows Virtual PC in XP Mode.

I am writing what I thought to be a pretty simple DOS program.  It is basically opening files, filling up structures, printing structure information to a file and that's it.  The files are binary and are less than 32 Kbytes, most are 1K or less.   I am 75% of the way done, it has been running fine up to now.  I just added some code to finish it off, and now I am getting this error at runtime:

"The NTDVM CPU has encountered an illegal instruction.
CS:00cc IP:0106 OP:ff ff 00 00 00 Choose 'Close' to terminate the application."

The thing is, the code I added is just a repeat of the same code that was at the beginning but to different structures.  Seems to have something to do with the code size?  I don't know.  I am not that familiar with memory management.  However, when I removed the stuff I had added, it works again.  

I am attaching both the main code and the extra code I am trying to add.

I would appreciate any guidance.
extracode.txt
main-code.txt
0
I`m a manual Quality Assurance. I really need an automation in my hard work. How should I good start? Have you any ideas? I use Selenium and C++ at my work. But is a basic C++ enough? I was thinking to go to college to take some C++ credits there. Maybe there something like https://domywriting.com/ which could help me in my work. I`m really lost in it because I don`t have the Computer science degree.
0
I have a friend who wants to learn to make video games.

I was wondering what to teach him , I was thinking of starting out with Dennis Ritchie’s “The C Programming language”

He wants to make a game within the next two years. That’s his goal.
0
I'm developing a game guard. And in the process, I want to read a packet and check its contents ... how should I do?

*(PDWORD)&OrigRecv = APIHook((DWORD)GetProcAddress(GetModuleHandle("Ws2_32.dll"), "recv"), (DWORD)MyRecv, (DWORD)OrigRecv);

Open in new window


my function recv

int WINAPI __stdcall MyRecv(SOCKET s, const char* buf, int len, int flags)
{
	int RecvedBytes = OrigRecv(s, buf, len, flags);
	if(RecvedBytes == SOCKET_ERROR) return RecvedBytes;

	eikasia_process_recv(s, (char *)buf, &RecvedBytes, flags); // Process the recived buffer
	return RecvedBytes;
}

Open in new window


My function process

void eikasia_process_recv(SOCKET s, char* buf, int *len, int flags) {
	unsigned int command = (*(unsigned short*)buf);


	if(command == 0x0363 ) {
 
     //reader buf data ...? read char* buf.... ?? help-me!

		}
	
}

Open in new window



When I find the packet I want to process, I want to read the contents of it to find the value I want. How to proceed?


my github: https://github.com/AsiaGenius/ring-0
0
I was trying to use wcstombs_s to convert my Japanese wstring into multibyte char but am getting empty string . Here's what i was doing my first approach using wcstombs_s -

wstring str = "ス";
char * outputString;
size_t outputSize = str.length() + 1; // +1 for null terminator
outputString = new char[outputSize];
size_t charsConverted = 0;
const wchar_t * inputW = str.c_str();
wcstombs_s(&charsConverted, outputString, outputSize, inputW, str.length());
i receive empty string in inputW,
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.

Vendor Experts

Gil FeldmanMonday Learn more about Monday