std::string to pointer to const char*

Posts 1–12 of 12 · Page 1 of 1
std::string to pointer to const char*
I'v got a function that looks like this..
Code:
std::string GetString(std::string key)
in my main program i'm trying to call this funtion. But then copy it to another STD::STRING so that i then can copy it to a const char*

Code:
std::string pet =  GetString("dog");
const char * newpet = pet.c_str();
If your wondering what the entire funtion looks like here it is...

Code:
std::string GetString(std::string key)
{
	//Check to see if anything got parsed?
	if (i == 0)
	{
		return "";
	}

	for (int x = 0; x <= i; x++)
	{
		if (key == iniItem[x]->key)
		{
			return iniItem[x]->value;
		}
	}

	return "";
}
whats your question?
Not able to copy the string to another string so that i can copy it to a Const char*
You won't be able to copy it into a const char* (notice the const part?). But you can do this:

Code:
std::string str = "This is a string";

char* ptr_str = (char*)str.data();

or you can:

std::string str = "This is another string":

char* ptr_str = new char[ str.size() + 1];

memcpy( (void*)ptr_str, (void*)str.data(), str.size() );
I recommend the second, because if you use the first method you can't let the string to out of scope. The second method leaves you with two usable copies.
well it has to copy it via the function as the function holds the string. And new and memcpy is C wich is a NONO in C++..
Quote Originally Posted by faceofdevil View Post
well it has to copy it via the function as the function holds the string. And new and memcpy is C wich is a NONO in C++..
Why using using memcpy a "NONO in C++"?
new[] is one of several features that define C++, it's an exclusive C++ keyword. You can't use new[] in C, since c uses malloc(). Memcpy is not a big nono in C++, it's part the of the standard library. Please explain what you want to do more clearly if you want help. I don't understand what you want to do.
Code:
std::string pet = GetString("dog");
char* new_pet = (char*)pet.data();
This doesnt work for some reason

Code:
std::string pet =  GetString("dog");
const char * newpet = pet.c_str();
doesnt work for some reason..

But this does..

Code:
std::cout << "New Pet: " << GetString("dog") << "\n"; //Return string
Any reason into fixing this issue....
i still dont get your point.. do you want to copy returned std::string from GetString to a new std::string variable?

if so try this:

Code:
std::string pet = GetString("dog");
std::string newpert = std::string(pet.c_str());
i know it could be done by other ways but its 4 : 10 AM here and i cant think well
It's probably because your std::string goes out of scope, and thus it's desxtructor is called. If you try to use a pointer when the string is no longer there you'll get undefined behavior.

But without your complete source I really can't be of much help, either the string is out of scope, or something else is wrong further in the code. Because assuming the getstring() function works properly, nothing is wrong with your code.

If the string goes out of scope, copy the characters into another buffer. Like this:


Code:
std::string str = GetString("dog");
char* Buffer = NULL;

if( str.size() )
{

Buffer = new char[ str.size() + 1 ];
memcpy( (void*)Buffer, (void*)str.data(), str.size() );

} else std::cout << "No string was returned by GetString()!" << std::endl;

...
...
// string goes out of scope or is destroyed somewhere..

..
..

std::cout << "New pet: " << Buffer << std::endl;
Here is the source code mabye this would help you more..

config.h
Code:
ifndef CONFIG_H
#define	CONFIG_H

#include <string>
#include <fstream>
#include <algorithm>
#include <iostream>
#include <functional>
#include <locale>
#include <cctype>
#include <cstdlib>
#include <winsock2.h>
#include <mysql.h>

/**
 * Parse a configuration file
 * 
 * @param	fileName The name of the file to parse
 * @return	none
 */
void parseIniFile(char *fileName);

/**
 * If you are finished with the config item, use this function to cleanup the results
 * 
 * @return none
 */
void cleanupIniReader();

/**
 * Return the value of the requested key in with the string type
 *
 * @param	key The option key
 * @return	string The value of the requested key
 */
std::string GetString(std::string key);

/**
 * Return the value of the requested key in with the int type
 *
 * @param	key The option key
 * @return	int The value of the requested key
 * @note	If item is not an integer (or does not exist) then 0 will be returned.
 */
int GetInt(std::string key);

/**
 * Return the value of the requested key in with the char type
 *
 * @param    key The option key
 * @return   char The value of the requested key
 */
const char *GetChar(std::string key);

std::string parseName(std::string value);
std::string parseValue(std::string value);
std::string trim(std::string s);
std::string rtrim(std::string s);
std::string ltrim(std::string s);

#endif	/* CONFIG_H */
config.cpp
Code:
#include "config.h"

struct ConfigItems
{
	std::string key;
	std::string value;
};
ConfigItems* iniItem[1024];

int i = 0;

void parseIniFile(char *fileName)
{
	std::string optionValue;
	std::ifstream infile;
	infile.open(fileName);

	//Does the file exist?
	if (infile.is_open() != true)
	{
		return;
	}

    std::string key;

	while (!infile.eof()) // To get you all the lines.
	{
		getline(infile, optionValue); // Saves the line in STRING.

		//Is the option a comment
		if (optionValue.substr(0, 1) == "#")
		{
			continue;
		}

		key = parseName(optionValue);

		if (key.length() > 0)
		{
			iniItem[i] = new ConfigItems;
			iniItem[i]->key = key;
			iniItem[i]->value = parseValue(optionValue);
			i++;
		}
	}

	i--;
	infile.close();
}

void cleanupIniReader()
{
	for (int x = 0; x <= i; x++)
	{
		delete iniItem[x];
	}

	i = 0;
}

std::string GetString(std::string key)
{
	//Check to see if anything got parsed?
	if (i == 0)
	{
		return "";
	}

	for (int x = 0; x <= i; x++)
	{
		if (key == iniItem[x]->key)
		{
			return iniItem[x]->value;
		}
	}

	return "";
}

const char *GetChar(std::string key)
{
	//Check to see if anything got parsed?
	if (i == 0)
	{
		return "";
	}

	for (int x = 0; x <= i; x++)
	{
		if (key == iniItem[x]->key)
		{
			return iniItem[x]->value.c_str();
		}
	}

	return "";
}

int GetInt(std::string key)
{
	//Check to see if anything got parsed?
	if (i == 0)
	{
		return 0;
	}

	for (int x = 0; x <= i; x++)
	{
		if (key == iniItem[x]->key)
		{
			return atoi(iniItem[x]->value.c_str());
		}
	}

	return 0;
}

std::string parseName(std::string value)
{
	size_t found;

	found = value.find('=');

	if (found > 100)
	{
		return "";
	}

	std::string key = value.substr(0, (found-1));
	key = trim(key);

	return key;
}

std::string parseValue(std::string value)
{
	size_t found;

	found = value.find('=');

	if (found > 100)
	{
		return "";
	}

	std::string keyValue = value.substr((found+1));
	keyValue = trim(keyValue);

	return keyValue;
}

std::string trim(std::string s)
{
	return ltrim(rtrim(s));
}

// trim from start
std::string ltrim(std::string s) 
{
        s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
        return s;
}

// trim from end
std::string rtrim(std::string s) 
{
        s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
        return s;
}
main.cpp
Code:
#include "config.h"

int main( int argc, char* argv[] )
{
	parseIniFile("config.ini");

	std::string pet = GetString("pet");
	char* new_pet = (char*)pet.data();

	cleanupIniReader();
	
	return 0;
}
This is the program but im doing something else with it.

But what i need to do is call the function copy the function's string and then pass it to a char* so that i can handle it from there...
Posts 1–12 of 12 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Need help?