I Expect to get the name which I sent to the "class stud" which has a class variable CHAR name
The issue appears specifically at this line this->name->set_name_send(OBJ.name->get_name());
and I get this error " -- invalid conversion from 'const char*' to 'char*' -- "
Any suggestions?
enter image description here
If I make the function set_name as a const and delete the pointers in the destructor code runs but return value is garbage and it has to be 0
Maybe the class *name doesn't have to be pointer ?
All pointer and in OOP
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
using namespace std;
class CHAR
{
char *name;
public:
CHAR(char *mes = "\0") {(this)->name = new char[100]; strcpy((this)->name,mes);}
CHAR(const CHAR&OBJ) { (this)->name = new char[100]; strcpy((this)->name,OBJ.name); }
~CHAR(){cout<<"CHAR Destructor!"<<endl; delete name;}
void set_name(char *mes){(this)->name = new char[100]; strcpy((this)->name,mes);}
const char* get_name() const {return (this)->name;}
};
class stud
{
CHAR *name;
public:
stud(char *mes)
{
this->name->set_name(mes);
}
stud( stud&OBJ)
{
this->name->set_name(OBJ.name->get_name()); //!!!!!!!!!!!!!!! issue HERE!!
}
~stud(){cout<<"Destructor!"<<endl;}
const char* get_name() const {return this->name->get_name();}
};
int main()
{
stud S("John");
stud A(S);
cout<<"Name: "<<A.get_name()<<endl;
}
Related
Task: to implement a Phone book management in C
What I did not understand exactly: I have to implement qsort to sort the phone book (lexicographically by last name and first name) which didnĀ“t work although I used the syntax exactly as it is displayed on the web page: https://www.tutorialspoint.com/c_standard_library/c_function_qsort.htm
The error message:
c:41:25: error: expected ')' before numeric constant
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char* vorname;
char* nachname;
char* telefonnummer;
} telefonbucheintrag;
void schreibe_eintrag(
telefonbucheintrag* eintrag_ptr,
char* vorname,
char* nachname,
char* telefonnummer)
{
eintrag_ptr->vorname = malloc(strlen(vorname)+1);
eintrag_ptr->nachname = malloc(strlen(nachname)+1);
eintrag_ptr->telefonnummer= malloc(strlen(telefonnummer)+1);
strcpy(eintrag_ptr->vorname, vorname);
strcpy(eintrag_ptr->nachname, nachname);
strcpy(eintrag_ptr->telefonnummer, telefonnummer);
}
int main()
{
telefonbucheintrag telefonbuch[100];
int32_t telefonbucheintraege = 0;
schreibe_eintrag(telefonbuch+0, "Ada", "Lovelace", "004917155669988");
schreibe_eintrag(telefonbuch+1, "Alan", "Turing", "004917155669922");
schreibe_eintrag(telefonbuch+2, "Ingo", "Mueller", "004917155669911");
schreibe_eintrag(telefonbuch+3, "Ilse", "Mueller", "004917155669933");
schreibe_eintrag(telefonbuch+4, "Stefan", "Sadat", "004917155669988");
telefonbucheintraege = 5;
qsort (telefonbuch, 5, sizeof(int), telefonbucheintraege );
}
replace sizeof(int) with sizeof(*telefonbuch) or what you have
I am creating a class that has two members string and int
I want to use the constructor to initialize both of these two members to use them.
#pragma once
#include <string>
#include <iostream>
using namespace std;
class donation_1
{
public:
//string name;
const char* name;
int donation_amount;
const static size_t string_size = sizeof(string);
const static size_t int_size = sizeof(int);
donation_1(char* name_1 = "Noname", int amount = 0) : name(name_1), donation_amount(amount) {};
};
int main()
{
fstream file;
file.open("donation_total1.txt", ios_base::app);
if (file.is_open())
{
donation_1("xxxx", 20).writedata(file);
donation_1("yyyy", 30).writedata(file);
donation_1("zzzz", 40).writedata(file);
donation_1("MMMM", 50).writedata(file);
donation_1("BBBB", 60).writedata(file);
file.close();
}
else
{
cout << "file couldn't be opened" << endl;
}
return 0;
}
I want to use the constructor to initialize the class variables which I will be using to update a file, however, what I am getting is this error. this error is regarding initializing the string class member.
Severity Code Description Project File Line Suppression State
Error (active) E0310 default argument of type "const char *" is incompatible with parameter of type "char *" Stream_File_Lab D:\INVSPRIVATE\C++\Projects\Stream_File_Lab\donation_1.h 17
The error message is makes it pretty clear. The variable 'name' is declared as const char* but the value being assigned to it is only char* i.e. the const-ness is missing, hence the type incompatibility error throws up.
Please, google for pointer to a const value and how to use them.
Maybe check this tutorial
I am getting these two errors
Error # 01:
error C2146: syntax error : missing ';' before identifier 'mainObj'
Error # 02
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
i have following classes
Main
Customer
CNode
when i create pointer object of class 'CNode' in class 'Customer' ,there is no error. But when i create non pointer object of Main class in Customer class
,compiler gives above two errors.
while 'Main' class have a main fuction.
please help me out to resolve these errors.
Main.h
#pragma once
#include <iostream>
#include<string>
#include<conio.h>
#include<fstream>
#include<iomanip>
#include <sstream>
#include "Customer.h"
using namespace std;
class Main
{
int acc;
int total = 0;
int rtotal = 0;
int sum = 0;
public:
Main();
void design();
void welcome();
string passcin();
void login_des();
void admin_account();
void add_staff();
void delete_staff(int);
void search_staff(int);
void update_staff(int);
void room_display();
void room_book();
void checkout();
int main();
};
Customer.h
#pragma once
#include <iostream>
#include<string>
#include<fstream>
#include <sstream>
#include "Main.h"
#include "Node.h"
class Customer
{
CNode *head, *tail, * temp;
Main mainObj;
public:
Customer();
bool search(string, string);
void updateAccount(string, string);
CNode* inputNode();
void custAccount(string);
void createAccount();
void createAccount(CNode *);
void addCust();
void deleteCust(int sno);
void searchCust(int sno);
void updateCust(int sno);
void displayCust();
CNode* retriveAllCust();
};
Node.h
#pragma once
#include <iostream>
#include<string>
#include<fstream>
using namespace std;
class CNode
{
string name, email, pass, roomNo, phoneNo, country, creditCardName, cardNo;
bool bookFlag;
CNode *prev, *next;
int length;
public:
CNode();
CNode(string n, string e, string ps, string r, string pn, string country, string creditName, string creditNo, bool bookFlag);
CNode(string n, string e, string ps, string pn, string country);
string getName();
string getPass();
CNode* getNextNode();
void display();
void addCust();
string retriveCust();
friend class Customer;
};
I have put a semi colon before mainObj
like
;Main mainObj;
error occors in Customer Class
in
Main mainObj;
I'm trying to use Boost library in my C++ Windows Form Application and I always get an exception:
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I'm using Visual Studio 2012 and Boost version 1.57.0. Previously I used Boost version 1.56.0 but upgrading didn't solve my issue.
Here are the code:
MyForm.cpp
#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
void main(cli::array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
TestUnmanaged::MyForm form;
Application::Run(%form);
}
MyForm.h
#pragma once
#include <iostream>
#include <map>
#include <sstream>
#include <cassert>
#include <stdio.h>
#include "ExternalProfileManager.h"
#define DEFAULT_PROFILE_NAME "profile.bin"
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "lib/edk.lib")
namespace TestUnmanaged {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
ExternalProfileManager profileManager;
/// <summary>
/// Summary for MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
profileManager.load(DEFAULT_PROFILE_NAME);
std::vector<std::string> profileList;
profileManager.listProfile(profileList);
}
ExternalProfileManager.h
#ifndef EXTERNAL_PROFILE_MANAGER_H
#define EXTERNAL_PROFILE_MANAGER_H
#include <boost/serialization/string.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/base_object.hpp>
class ExternalProfileManager
{
ExternalProfileManager(const ExternalProfileManager&) {};
ExternalProfileManager& operator = (const ExternalProfileManager&) {};
protected:
std::map<std::string, std::string > _profiles;
typedef std::map<std::string, std::string >::iterator profileItr_t;
// Boost serialization support
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int /*file version */)
{
ar & _profiles;
}
public:
ExternalProfileManager();
virtual ~ExternalProfileManager();
virtual bool save(const std::string& location);
virtual bool load(const std::string& location);
virtual bool insertProfile(const std::string& name, const unsigned char* profileBuf, unsigned int bufSize);
virtual bool listProfile(std::vector<std::string>& profiles);
};
//BOOST_CLASS_EXPORT(ExternalProfileManager);
//BOOST_CLASS_TRACKING(ExternalProfileManager, boost::serialization::track_never);
#endif // EXTERNAL_PROFILE_MANAGER_H
ExternalProfileManager.cpp
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/regex.hpp>
#pragma warning(push)
#pragma warning(disable : 4267) // "conversion from size_t to unsigned int"
#pragma warning(disable : 4996)
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#pragma warning(pop)
#include "ExternalProfileManager.h"
using namespace std;
namespace fs = boost::filesystem;
ExternalProfileManager::ExternalProfileManager()
{
}
ExternalProfileManager::~ExternalProfileManager()
{
}
bool ExternalProfileManager::save(const string& location)
{
ofstream ofs(location.c_str(), ios_base::binary);
if ( !ofs.is_open() ) return false;
try {
boost::archive::binary_oarchive oa(ofs);
oa << *this;
}
catch (boost::archive::archive_exception& )
{
return false;
}
return true;
}
bool ExternalProfileManager::load(const string& location)
{
ifstream ifs(location.c_str(), ios_base::binary);
if ( !ifs.is_open() ) return false;
try {
boost::archive::binary_iarchive ia(ifs);
ia >> *this;
}
catch (boost::archive::archive_exception& )
{
return false;
}
return true;
}
bool ExternalProfileManager::insertProfile(const string& name, const unsigned char* profileBuf, unsigned int bufSize)
{
assert(profileBuf);
// Replace our stored bytes with the contents of the buffer passed by the caller
string bytesIn(profileBuf, profileBuf+bufSize);
_profiles[name] = bytesIn;
return true;
}
bool ExternalProfileManager::listProfile(vector<string>& profiles)
{
profiles.clear();
for ( profileItr_t itr = _profiles.begin(); itr != _profiles.end(); ++itr ) {
profiles.push_back(itr->first);
}
return true;
}
The error occurred in ia >> *this; in ExternalProfileManager::load (thrown in file basic_archive.cpp). So calling profileManager.load(DEFAULT_PROFILE_NAME); from form constructor will trigger the exception.
Calling save will also trigger the same exception but other functions which have no this will work fine.
I tried creating a console application in VS 2012 and call ExternalProfileManager.h and it works perfectly (including save, load, and any other function). Here are the simple console application I created to test it:
Console.cpp
#include <iostream>
#include <map>
#include <sstream>
#include <cassert>
#include <stdio.h>
#include "ExternalProfileManager.h"
#define DEFAULT_PROFILE_NAME "profile.bin"
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "lib/edk.lib")
ExternalProfileManager profileManager;
int main(int argc, char** argv) {
profileManager.load(DEFAULT_PROFILE_NAME);
std::vector<std::string> profileList;
profileManager.listProfile(profileList);
std::cout << "Available profiles:" << std::endl;
for (size_t i=0; i < profileList.size(); i++) {
std::cout << i+1 << ". " << profileList.at(i);
if (i+1 < profileList.size()) {
std::cout << std::endl;
}
}
return true;
}
profile.bin is generated from calling save function in console application and contain serialized data generated by boost. I can provide the file if it is needed to solve this issue.
I have also tried to create a simple class wrapper but the exception still occurred.
WrapperExternalProfileManager.h
#ifndef WRAPPER_EXTERNAL_PROFILE_MANAGER_H
#define WRAPPER_EXTERNAL_PROFILE_MANAGER_H
#include <string>
#include <vector>
class WrapperExternalProfileManager
{
WrapperExternalProfileManager(const WrapperExternalProfileManager&) {};
WrapperExternalProfileManager& operator = (const WrapperExternalProfileManager&) {};
public:
WrapperExternalProfileManager();
virtual ~WrapperExternalProfileManager();
virtual bool save(const std::string& location);
virtual bool load(const std::string& location);
virtual bool insertProfile(const std::string& name, const unsigned char* profileBuf, unsigned int bufSize);
virtual bool listProfile(std::vector<std::string>& profiles);
};
#endif
WrapperExternalProfileManager.cpp
#include "WrapperExternalProfileManager.h"
#include "ExternalProfileManager.h"
using namespace std;
ExternalProfileManager profileManager;
WrapperExternalProfileManager::WrapperExternalProfileManager()
{
std::cout<<"Constructor WrapperExternalProfileManager"<<std::endl;
}
WrapperExternalProfileManager::~WrapperExternalProfileManager()
{
}
bool WrapperExternalProfileManager::save(const string& location)
{
return profileManager.save(location);
}
bool WrapperExternalProfileManager::load(const string& location)
{
return profileManager.load(location);
}
bool WrapperExternalProfileManager::insertProfile(const string& name, const unsigned char* profileBuf, unsigned int bufSize)
{
return profileManager.insertProfile(name, profileBuf, bufSize);
}
bool WrapperExternalProfileManager::listProfile(vector<string>& profiles)
{
return profileManager.listProfile(profiles);
}
save and load still trigger the exception but other functions work perfectly.
Here are some property of the application which might be helpful:
Linker -> System -> SubSystem: Windows (/SUBSYSTEM:WINDOWS)
General -> Common Language Runtime Support: Common Language Runtime Support (/clr)
I know I have done something incorrectly but I don't know which part. Any suggestion to solve this issue would be appreciated.
Thanks in advance
You're going to have to find the source of your Undefined Behaviour (use static analysis tools, heap checking and divide and conquer).
I've just built your code on VS2013 RTM, using a ultra-simple C# console application as the driver:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var f = new TestUnmanaged.MyForm();
f.ShowDialog();
}
}
}
This JustWorks(TM).
I created a profile.bin with 100 random profiles of varying length:
#if 1
for (int i = 0; i < 100; ++i)
{
std::vector<uint8_t> buf;
std::generate_n(back_inserter(buf), rand() % 1024, rand);
insertProfile("profile" + std::to_string(i), buf.data(), buf.size());
}
save(location);
#endif
And they are deserialized just fine.
Good luck.
Download the full project here http://downloads.sehe.nl/stackoverflow/q27032092.zip in case you want to fiddle with it (compare the details?)
I have a function in C++ that have a value in std::string type and would like to convert it to String^.
void(String ^outValue)
{
std::string str("Hello World");
outValue = str;
}
From MSDN:
#include <string>
#include <iostream>
using namespace System;
using namespace std;
int main() {
string str = "test";
String^ newSystemString = gcnew String(str.c_str());
}
http://msdn.microsoft.com/en-us/library/ms235219.aspx
Googling reveals marshal_as (untested):
// marshal_as_test.cpp
// compile with: /clr
#include <stdlib.h>
#include <string>
#include <msclr\marshal_cppstd.h>
using namespace System;
using namespace msclr::interop;
int main() {
std::string message = "Test String to Marshal";
String^ result;
result = marshal_as<String^>( message );
return 0;
}
Also see Overview of Marshaling.
As far as I got it, at least the marshal_as approach (not sure about gcnew String) will lead to non ASCII UTF-8 characters in the std::string to be broken.
Based on what I've found on https://bytes.com/topic/c-sharp/answers/725734-utf-8-std-string-system-string I've build this solution which seems to work for me at least with German diacritics:
System::String^ StdStringToUTF16(std::string s)
{
cli::array<System::Byte>^ a = gcnew cli::array<System::Byte>(s.length());
int i = s.length();
while (i-- > 0)
{
a[i] = s[i];
}
return System::Text::Encoding::UTF8->GetString(a);
}