Debug assertion failed error on using class function C++ Visual Studio - c++

I'm new to C++
Code:
#include <iostream>
#include <string>
#include <fstream>
#include <windows.h>
class spawnTools {
private:
void specTools(std::string toolname) {
}
void normTools(std::string toolname) {
}
public:
std::string toolList =
{ "regedit", "cmd" };
std::string toolListAdmin =
{ "regedit", "cmd" };
void initToolSet(int xadmin) {
if (xadmin == TRUE) {
}
else if (xadmin == FALSE) {
}
else {
MessageBox(NULL, L"SYSTEM ERROR: Incorrect input into xadmin", L"Error", MB_OK | MB_ICONERROR);
}
}
};
int main() {
spawnTools st;
st.initToolSet(TRUE); <----- Exception thrown here
}
I have set up a class with 2 public strings and 1 public function.
The private functions will be filled in later in the development (just so you know I'm not hiding any code).
I'm getting an Debug Assertion error that says I have a transposed pointer range; it's not like this question as I'm using std::strings, not a vector char.
And anyway the exception is thrown on the usage of the public function, not the std::strings.
I have tried using ' commas on the std::strings instead of the normal " commas, but that throws another error, so that doesn't work.
I have tried using struct in case it's to do with class. No luck.

You cannot initialize a std::string with two strings that way. The C strings "regedit" and "cmd" are being passed to a constructor that is normally used to pass start and end iterators of the string you want to initialize it with. This results in it attempting to initialize the string with the the address of "regedit" as the start iterator (address) of the string and the address of "cmd" as the end iterator (address) of the string. The assert you are getting is because the address of "cmd" is lower than "regedit".
Chances are you're going to want a std::array<std::string, 2> or std::vector<std::string> or even a naked std::string[2] array to hold them.
#include <string>
#include <array>
#include <windows.h>
class spawnTools
{
private:
void specTools(std::string toolname) {}
void normTools(std::string toolname) {}
public:
std::array<std::string, 2> toolList{ "regedit", "cmd" };
std::array<std::string, 2> toolListAdmin{ "regedit", "cmd" };
void initToolSet(int xadmin) {
if (xadmin == TRUE) {}
else if (xadmin == FALSE) {}
else {
MessageBox(
NULL,
L"SYSTEM ERROR: Incorrect input into xadmin",
L"Error",
MB_OK | MB_ICONERROR);
}
}
};
int main() {
spawnTools st;
st.initToolSet(TRUE);
}

Related

File pointer does not works when moved to a class?

So I found this solution to call a python script and it works in Microsoft Visual Studio Professional 2019 Version 16.6.2. I moved the three methods into a separate class and it no longer works. I thought I could figure it out but have just been beating myself up so I am here asking for help from readers who are much more knowledgeable than myself. The working code follows.
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
#include <iostream>
#include <string>
void close_file(std::FILE* fp) {
std::fclose(fp);
}
std::string exec_python(const char* scriptCommand) {
std::array<char, 256> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&close_file)> _pipe(_popen(scriptCommand, "r"), close_file);
if (!_pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), static_cast<int>(buffer.size()), _pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
std::string call_script(std::string ScriptLoc, std::string Script_Parameters) {
std::string ScriptInput = ScriptLoc + " " + Script_Parameters;
std::string result = exec_python(ScriptInput.c_str());
return result;
}
int main()
{
std::string LOne = "python.exe \"C:\\Users\\.....\\source\\repos\\PyApplication1\\PyApplication1.py\"";
std::string LTwo = " Message";
//system(LTwo.c_str());
std::string oRez=call_script(LOne,LTwo);
std::cout <<"Results:"+oRez << std::endl;
}
The separate class that will not compile and related error messages follow. first is the header file, iTool.h.
#pragma once
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
#include <iostream>
#include <string>
class iTool {
public:
void close_file(std::FILE* fp);
std::string exec_python(const char* scriptCommand);
std::string call_script(std::string ScriptLoc, std::string Script_Parameters);
iTool();
};
The second is the iTool.cpp.
#include "iTool.h"
void iTool::close_file(std::FILE* fp) {
std::fclose(fp);
}
std::string iTool::exec_python(const char* scriptCommand) {
std::array<char, 256> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&close_file)> _pipe(_popen(scriptCommand, "r"), close_file);
if (!_pipe) {
//throw std::runtime_error("_popen() failed!");
} else { throw std::runtime_error("_popen() failed!"); }
while (fgets(buffer.data(), static_cast<int>(buffer.size()), _pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
std::string iTool::call_script(std::string ScriptLoc, std::string Script_Parameters) {
std::string ScriptInput = ScriptLoc + " " + Script_Parameters;
std::string result = exec_python(ScriptInput.c_str());
return result;
}
iTool::iTool() = default;
The error messages.:
Severity Code Description Project File Line Suppression State
Error C2088 '!': illegal for class TestAppliance1 C:\Users\....\source\repos\TestAppliance1\iTool.cpp 11
Error C2276 '&': illegal operation on bound member function expression TestAppliance1 C:\Users\...\source\repos\TestAppliance1\iTool.cpp 10
Error C2514 'std::unique_ptr': class template cannot be constructed TestAppliance1 C:\Users\...\source\repos\TestAppliance1\iTool.cpp 10
Error C2660 'fgets': function does not take 2 arguments TestAppliance1 C:\Users\...\source\repos\TestAppliance1\iTool.cpp 14
Error C2662 '_Get_deleter_pointer_type<_Ty,remove_reference<_Ty1>::type,void>::type std::unique_ptr<_Ty,_Dx>::get(void) noexcept const': cannot convert 'this' pointer from 'std::unique_ptr' to 'const std::unique_ptr<_Ty,_Dx> &' TestAppliance1 C:\Users\...\source\repos\TestAppliance1\iTool.cpp 14
Thanks for your help!
You tripped over a non-static member function having a hidden this parameter and not matching the prototype expected for a deleter function.
Instead of void (*)(std::File*), the proposed deleter looks something like void (iTool::*(std::File*)
You can solve the problem by wrapping the function call with a lamda expression that captures this, but since close_file doesn't use this (something wrong with that--fp should probably be a member variable--that is outside the scope of this question), lets go with making it a static member function. The asker can clean up the ideological problems later.
In the iTool class definition,
void close_file(std::FILE* fp);
becomes
static void close_file(std::FILE* fp);
After you create a class you must create an instance of that class in the main function before you can use it:
iTool tool()
Inside you mean function.....
Also one word of caution for you my friend, if you do not know what:
iTool::iTool() = default;
Sets your variables to please do not use it...... You can always define those variables by yourself in your private part, if you know what the default does, by all means go ahead.

Use a struct in another struct

Hi there I keep getting error for the code below which I think makes sense!
I'm trying to use a member of the first struct in a function in the second struct. I code in Xcode and this is the error I get:
No member named 'PLZ' in 'std::__1::vector >'
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct place {
string PLZ;
string name;
};
struct adresse {
string firstN;
string lastN;
string Str;
string Hsnum;
string PLZ;
void print(vector<place> a){
cout<<a.PLZ;
}
};
int main()
{
return 0;
}
Just define the function at least like
void print(const vector<place> &a) const
{
for ( const auto &place : a )
{
cout << place.PLZ << ' ';
}
}
std::vector is a container that can contain several elements. So you have to specify whether you are going to output all elements of a vector or a concrete element.
The function above outputs the data member PLZ of each element of the vector.

Having trouble writing stack implementation c++

I am building a programming language interpreter, and I am currently working on writing the stack code. Write now the stack will only hold byte values, but it will be extended to hold other bytes as well. At the moment I am having trouble with casting between 'BaseObject' that all my stack objects extend and my jbyte class. Here is my current test code.
#include "stdafx.h"
#include <string>
#include <stack>
#include <iostream>
#include <Windows.h>
#include <stack>
using namespace std;
class BaseObject
{
public:
virtual string getIdentifier(){return "Not Implemented";}
};
class Stack
{
class jbyte : public BaseObject
{
private:
INT8 byteValue;
public:
jbyte(INT8 value)
{
byteValue = value;
}
INT8 getValue()
{
return byteValue;
}
};
private:
stack<BaseObject> objectStack;
public:
void pushByte(INT8 byteValue)
{
jbyte toPush(byteValue);
objectStack.push(toPush);
}
INT8 popByte()
{
if(objectStack.size() == 0)
{
cout<<"ERROR: Trying To Pop Value From Empty Stack\nPress Any Key To Continue...";
_gettch();
exit(1);
}
else
{
BaseObject& bo = objectStack.top();
jbyte& b = dynamic_cast<jbyte&>(bo);
}
}
};
int main()
{
Stack stack;
stack.pushByte(9);
stack.popByte();
while(true);
}
When I try to run this however, I get an Unhandled exception at at 0x75C4C41F in StackTests.exe: Microsoft C++ exception: std::bad_cast at memory location 0x0034F858.
I would like to know how to fix this problem, or if that is difficult, how I could rewrite the stack to work successfully.
When you objectStack.push(toPush), the jbyte part of toPush is sliced off and only the BaseObject part remains. That's why casting the BaseObject back to jbyte is no longer possible.

class objects as data members and header file includes

I'm currently putting together what I've learned of C++ by writing a small text adventure - just trying to get the basic class interrelations down so I can have the player move through a few rooms at the moment. I'm getting an 'expected unqualified id before '}' error in my room.h file when I compile. I think it may have something to do with a Room class member which is a vector of Exit object pointers, but I'm not sure. I'd appreciate a quick scan of the code just to let me know If I'm missing something obvious but important. Sorry if this gets complicated. I'll try to be brief and to the point.
I'm not sure what you all may need to see (codewise) and I don't want to throw up the whole code so...Let me outline how I have things set up, to start off with.:
1) I have a cpp file, called from main(), which instantiates 21 new rooms on the heap
2) Followed by another cpp file which instantiates new Exit objects on the heap, pushes them onto a vector, and calls a Room.set() function to pass the vector of Exit pointers to the Room class as one of its data members. Each exit in The vector will also have a pointer to one of the new Rooms created on the Heap.
The file to instantiate new rooms looks like this:
#include "RoomsInit.h"
#include "Room.h"
void InstantiateRooms()
{
string roomName1 = "On a deserted beach";
string roomDescr1 = "You are standing on a deserted beach. To the east, a "
"crystal blue ocean\n dances in the morning sun. To the "
"west is a dense jungle, and somewhere\n far off, you can "
"hear the singing of a strange bird. The white, sandy \n"
"beach runs out of sight to the north and south.\n\n\n";
Room* p_deserted_beach = new Room(roomName1, roomDescr1);
* Only the roomName and roomDescr is passed to the constructor at this point...and there are 20 more rooms like this in the file.
The Exit instantiate file looks like this:
#include "exitsInit.h"
#include "exit.h"
#include "room.h"
#include "RoomsInit.h"
void InstantiateExits()
{
vector<Exit*> exitVec;
Exit* p_north1 = new Exit("north", p_on_the_beach_north, true, false);
Exit* p_south1 = new Exit("south", p_on_the_beach_south1, true, false);
Exit* p_east1 = new Exit("east", p_in_the_ocean, true, false);
Exit* p_west1 = new Exit("west", p_in_the_jungle, true, false);
exitVec.push_back(p_north1);
exitVec.push_back(p_south1);
exitVec.push_back(p_east1);
exitVec.push_back(p_west1);
(*p_deserted_beach).SetExitVec(exitVec);
exitVec.clear();
The exitVec is created and sent to the Room class via the set function to become one of it's data members...There are 20 more sets of these in this file)one for each room).
My Room class header file, where I'm getting the compiler error, at the moment, looks like this:
#ifndef ROOM_H_INCLUDED
#define ROOM_H_INCLUDED
#include <iostream>
#include <string>
#include <vector>
class Exit;
using namespace std;
class Room
{
private:
string m_roomName;
string m_roomDescr;
string m_specDescr;
bool m_isSpecDescr;
vector<Exit*> m_exitVec;
public:
Room(string roomName, string roomDescr, string specDescr = "",
bool isSpecDescr = false);
string GetRoomName(); const
string GetRoomDes(); const
bool GetRoomSpecBool(); const
string GetRoomSpec(); const
void SetExitVec(vector<Exit*> exitVec);
vector<Exit*> GetExitVec(); const
};
#endif // ROOM_H_INCLUDED
----------- with the corresponding cpp file: --------------
#include "room.h"
Room::Room(string roomName, string roomDescr,
string specDescr, bool isSpecDescr) :
m_roomName(roomName), m_roomDescr(roomDescr),
m_specDescr(specDescr), m_isSpecDescr(isSpecDescr) {}
string Room::GetRoomName() const
{
return m_roomName;
}
string Room::GetRoomDes() const
{
return m_roomDescr;
}
bool Room::GetRoomSpecBool() const
{
return m_isSpecDescr;
}
string Room::GetRoomSpec() const
{
return m_specDescr;
}
void Room::SetExitVec(vector<Exit*> exitVec)
{
m_exitVec = exitVec;
}
vector<Exit*> Room::GetExitVec() const
{
return m_exitVec;
}
---------The Exit class header is this:
#ifndef EXIT_H_INCLUDED
#define EXIT_H_INCLUDED
#include <iostream>
#include <string>
#include <vector>
class Room; // For using a class pointer as a data member
using namespace std;
class Exit
{
private:
string m_exitName; // east, west, etc
Room* mp_exitTo;
bool m_isExit;
bool m_isExitHidden;
bool m_isExitPhrase;
string m_exitPhrase;
public:
Exit();
Exit(string exitName, Room* pExit, bool isExit, bool isExitHidden,
bool isExitPhrase = false, string exitPhrase = "");
string GetExitName(); const
Room* GetExitTo(); const
void SetIsExitTrue();
void SetIsExitFalse();
bool GetIsExit(); const
void SetIsExitHiddenTrue();
void SetIsExitHiddenFalse();
bool GetIsExitHidden(); const
bool GetIsExitPhrase(); const
string GetExitPhrase(); const
};
#endif // EXIT_H_INCLUDED
-------------and its cpp file:
#include "room.h"
#include "exit.h"
#include "RoomsInit.h"
Exit::Exit() :
mp_exitTo(NULL), m_isExit(false), m_isExitHidden(false) {}
Exit::Exit(string exitName, Room* pExit, bool isExit, bool isExitHidden,
bool isExitPhrase, string exitPhrase) :
m_exitName(exitName), mp_exitTo(pExit), m_isExit(isExit),
m_isExitHidden(isExitHidden), m_isExitPhrase(isExitPhrase),
m_exitPhrase(exitPhrase) {}
string Exit::GetExitName() const
{
return m_exitName;
}
Room* Exit::GetExitTo() const
{
return mp_exitTo;
}
void Exit::SetIsExitTrue()
{
m_isExit = true;
}
void Exit::SetIsExitFalse()
{
m_isExit = false;
}
bool Exit::GetIsExit() const
{
return m_isExit;
}
void Exit::SetIsExitHiddenTrue();
{
m_isExitHidden = true;
}
void Exit::SetIsExitHiddenFalse();
{
m_isExitHidden = false;
}
bool Exit::GetIsExitHidden() const
{
return m_isExitHidden;
}
bool Exit::GetIsExitPhrase(); const
{
return m_isExitPhrase;
}
string Exit::GetExitPhrase() const
{
return m_exitPhrase;
}
I'm also getting 21 warnings stating that the rooms I've created on the Heap are unused variables - not sure what that means. I feel like I'm missing something about the #includes relationships that is crucial, but I just can't see what it is...I've only been programming for about 8 months and most of the examples I've come across in books or online are somewhat less complex than what I'm doing right now. And so, I'd really appreciate any advice or comments y'all who are more experienced might have. Thanks. - Mark
In room.h
string GetRoomName(); const
string GetRoomDes(); const
bool GetRoomSpecBool(); const
string GetRoomSpec(); const
void SetExitVec(vector<Exit*> exitVec);
vector<Exit*> GetExitVec(); const
should be
string GetRoomName() const;
string GetRoomDes() const;
bool GetRoomSpecBool() const;
string GetRoomSpec() const;
void SetExitVec(vector<Exit*> exitVec);
vector<Exit*> GetExitVec() const;
You got your semi-colons in the wrong place.

Calling a member function pointer stored in a std map

I'm storing a map in a class that has strings as keys and pointers to member functions as values. I'm having trouble calling the right function throw the function pointer.
Here is the code:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Preprocessor;
typedef void (Preprocessor::*function)();
class Preprocessor
{
public:
Preprocessor();
~Preprocessor();
void processing(const string before_processing);
private:
void take_new_key();
map<string, function> srch_keys;
string after_processing;
};
Preprocessor::Preprocessor()
{
srch_keys.insert(pair<string, function>(string("#define"), &Preprocessor::take_new_key));
}
Preprocessor::~Preprocessor()
{
}
void Preprocessor::processing(const string before_processing)
{
map<string, function>::iterator result = srch_keys.find("#define");
if(result != srch_keys.end())
result->second;
}
void Preprocessor::take_new_key()
{
cout << "enters here";
}
int main()
{
Preprocessor pre;
pre.processing(string("...word #define other word"));
return 0;
}
In function Preprocessor::processing if the string is found in the map then, I call the proper function. The problem is that, in this code, Preprocessor::take_new_key is never called.
Where is the mistake ?
Thanks
The correct syntax is this:
(this->*(result->second))();
That is ugly. So lets try this:
auto mem = result->second; //C++11 only
(this->*mem)();
Use whichever makes you happy.
result->second does not call the function pointer. Try ((*this).*result->second)();