• Advertisement
Sign in to follow this  

Unity Standard C++ Library Common Code Collaboration

This topic is 4363 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The other day I started messing around with making a scripting language just to see how I'd go about making one. As I was going though, I noticed a lot of my code could be greatly simplified with various stl functions that have been posted around GD. After using quite a lot of them, I figured it'd be nice to have them all in once place for further reference. So what follows is a little collection that I have so far. I have linked to where the original function was taken from. Now, I'm sure there are a lot of other neat useful functions to be added, so if you want to submit for this list, here is the template to follow. As you can see, html entities are removed so when you paste in your code, the tags are kept so it can easily be added to this post. Now, for the rules so this doesn't get too out of hand or unmanagable 1. If you don't like the standard C++ library, then this thread is where you can submit your comments. 2. Only functions that can be easily copied/pasted into a project and be explained. No classes or lots of complex code because they tend to be bigger need more explanations of how to use, and etc... For example, I have a templated manager class that would not belong here. There is also a great thread on encrypting strings using the TEA library. That code does not belong here either. 3. No Boost examples. Boost is a great library that probabally has a lot of functions that could make a lot of stuff presented here easier, but that's not the goal of this thread. I'll leave that at that. 4. Please fill out the template. Write a short test program that shows how the function works and save the output. This is to ensure accruate code is kept so people don't have problems trying to use the code presented here. If you take code from a post on GameDev, fill out the correct URL for reference. If you don't want to, well I'll end up doing it, but it'd be easier if you did [smile] 5. The issue of what to submit is kinda tricky. Somethings are obvious to some people and simply amazing to others. A good example is that a lot of people might not know there is a random_shuffle algorithm avaliable. So making a function that wraps that algoirhm so the user can just call Shuffle(vector) would be ok because of other alternatives posted on the net. The goal of this thread is to share modern knowledge of different things that can be useful to beginners though experts. This thread isn't meant to make up for people not knowing the Standard C++ Library, but rather as an encouragement to learn some of the more advanced things in it. Hopefully, it will be a good resource for a while! Thare are threads like this one that have great code, but unfortunately no one will probabally ever see again. For more examples of using the STL, take a look at this MSDN collection. There are many more as well, but code from sites like those should not be posted here. Also, if anyone sees anything that is wrong, or could possibly be done better, feel free to share. There are anchors used in this thread, so when you refer to code in it, you can use the anchor link to direct to a specific function. With that said...
Table of Contents: FileToString FileToVector lexer_merge_previous_append lexer_merge_previous_prepend lexer_merge_next_append lexer_merge_next_prepend ParseString RemoveAdjacentRepetitions TokenizeString TrimString StringContainsNone StringContainsOnly StringReplace StringToLower StringToUpper ToString
Title: StringReplace Description: Will replace "num_times" instances of "find_this" with "replace_with". If num_times is set to a negative number, all instances are replaced. URL: Original design Source:
void StringReplace(std::string& source, const std::string& find_this, const std::string& replace_with, int num_times = -1)
{
	int loc = 0;
	for(int i = 0; i != num_times; i++)
	{
		loc = source.find(find_this, 0);
		if (loc != -1) 
			source.replace(loc, find_this.length(), replace_with);
		else
			return;
	}
}

Example:
#include <iostream>
#include <string>

void StringReplace(std::string& source, const std::string& find_this, const std::string& replace_with, int num_times = -1)
{
	int loc = 0;
	for(int i = 0; i != num_times; i++)
	{
		loc = source.find(find_this, 0);
		if (loc != -1) 
			source.replace(loc, find_this.length(), replace_with);
		else
			return;
	}
}

int main(int argc, char* argv[])
{
	// Test 1 shows how to use without using the 'num_times'
	std::string source = "This is a test.";
	std::cout << source << std::endl;
	StringReplace(source, "i", "-");
	std::cout << source << std::endl << std::endl;

	// Test 2 shows how to use using 'num_times' as being 1
	source = "This is a test.";
	std::cout << source << std::endl;
	StringReplace(source, "i", "-", 1);
	std::cout << source << std::endl << std::endl;

	return 0;
}

Output:
This is a test.
Th-s -s a test.

This is a test.
Th-s is a test.

Press any key to continue

Title: FileToString Description: Will load a file with the given path of "filename" and return the contents of that file. If the file cannot be opened or does not exist, an empty string will be returned. URL: Original design Source:
std::string FileToString(const std::string &filename)
{
	std::ifstream fin(filename.c_str());
	return std::string((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>());
}

Example:
#include <iostream>
#include <fstream>
#include <string>

std::string FileToString(const std::string &filename)
{
	std::ifstream fin(filename.c_str());
	return std::string((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>());
}

int main(int argc, char* argv[])
{
	// Load this file into a string
	std::string myFile = FileToString("main.cpp");
	std::cout << myFile << std::endl;

	// Try and load a non-existant file
	myFile = FileToString("no-exist.zyx");
	if(myFile.size() == 0)
	{
		std::cout << "File is empty or does not exists" << std::endl;
	}

	return 0;
}

Output:
<< Main.cpp contents >>
File is empty or does not exists
Press any key to continue

Title: ParseString Description: This function will parse the "source" string into a vector of tokens based on spaces. Any group of tokens enclosed in 'token' are read as one token. URL: Original design Source:
std::vector<std::string> ParseString(const std::string& source, const char& token)
{
	using namespace std;
	vector<string> result;
	string item;
	stringstream ss(source);
	while(ss >> item)
	{
		if (item[0] == token) 
		{
			if(item[item.length() - 1] == token)
				result.push_back(item.substr(1, item.length()-2));
			else
			{
				string restOfItem;
				getline(ss, restOfItem, token);
				result.push_back(item.substr(1) + restOfItem);
			}
		}
		else
			result.push_back(item);
	}
	return result;
}

Example:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

std::vector<std::string> ParseString(const std::string& source, const char& token)
{
	using namespace std;
	vector<string> result;
	string item;
	stringstream ss(source);
	while(ss >> item)
	{
		if (item[0] == token) 
		{
			if(item[item.length() - 1] == token)
				result.push_back(item.substr(1, item.length()-2));
			else
			{
				string restOfItem;
				getline(ss, restOfItem, token);
				result.push_back(item.substr(1) + restOfItem);
			}
		}
		else
			result.push_back(item);
	}
	return result;
}

int main(int argc, char* argv[])
{
	std::string source = "-This is- a test of -how to parse- by token.";
	
	// Parse the string grouping wors by the '-' character
	std::vector<std::string> parsedTokens = ParseString(source, '-');

	for(int x = 0; x < parsedTokens.size(); x++)
		std::cout << parsedTokens[x] << std::endl;

	return 0;
}

Output:
This is
a
test
of
how to parse
by
token.
Press any key to continue

Title: TrimString Description: This function will remove all white space leading and following a string. URL: None Source:
void TrimString(std::string& source)
{
	int x = 0;
	for(x; x < source.size(); x++)
	{
		if(!isspace(source[x]))
			break;
	}
	source = source.substr(x);
	for(x = source.size() - 1; x >= 0; x--)
	{
		if(!isspace(source[x]))
			break;
	}
	source = source.substr(0, x + 1);
}

Example:
#include <iostream>
#include <string>

void TrimString(std::string& source)
{
	int x = 0;
	for(x; x < source.size(); x++)
	{
		if(!isspace(source[x]))
			break;
	}
	source = source.substr(x);
	for(x = source.size() - 1; x >= 0; x--)
	{
		if(!isspace(source[x]))
			break;
	}
	source = source.substr(0, x + 1);
}

int main(int argc, char* argv[])
{
	std::string source = "   This string needs trimming   ";
	std::cout << "Original string: " << source << std::endl;
	TrimString(source);
	std::cout << "Trimmed string: " << source << std::endl;
	return 0;
}

Output:
Original string:    This string needs trimming
Trimmed string: This string needs trimming
Press any key to continue

Title: StringContainsOnly Description: This function will return true if a string is only composed of the "validChars". It will return false if the string is composed of a character that is not part of the "validChars" string passed in URL: Original design Source:
bool StringContainsOnly(const std::string& source, const std::string& validChars)
{
	return (source.find_first_not_of(validChars) == std::string::npos);
}

Example:
#include <iostream>
#include <string>

bool StringContainsOnly(const std::string& source, const std::string& validChars)
{
	return (source.find_first_not_of(validChars) == std::string::npos);
}

int main(int argc, char* argv[])
{
	std::string source = "0123456789";
	if(StringContainsOnly(source, "13579"))
	{
		std::cout << "String only contains only odd digits" << std::endl;
	}
	else if(StringContainsOnly(source, "02468"))
	{
		std::cout << "String only contains even digits" << std::endl;
	}
	else if(StringContainsOnly(source, "0123456789"))
	{
		std::cout << "String only contains digits" << std::endl;
	}

	source = "13579";
	if(StringContainsOnly(source, "13579"))
	{
		std::cout << "String only contains only odd digits" << std::endl;
	}
	else if(StringContainsOnly(source, "02468"))
	{
		std::cout << "String only contains even digits" << std::endl;
	}
	else if(StringContainsOnly(source, "0123456789"))
	{
		std::cout << "String only contains digits" << std::endl;
	}

	return 0;
}

Output:
String only contains digits
String only contains only odd digits
Press any key to continue

Title: StringContainsNone Description: This function will return true of 'source' does not contain any of the characters in 'chars' or false otherwise. URL: None Source:
bool StringContainsNone(const std::string& source, const std::string& chars)
{
	return (source.find_first_of(chars) == std::string::npos);
}

Example:
#include <iostream>
#include <string>

bool StringContainsNone(const std::string& source, const std::string& chars)
{
	return (source.find_first_of(chars) == std::string::npos);
}

int main(int argc, char* argv[])
{
	std::string source = "abcdefghijklmnopqrstuvwxyz";
	
	if(StringContainsNone(source, "aeiou"))
	{
		std::cout << "String does not contain any vowels" << std::endl;
	}
	else
	{
		std::cout << "String contain vowels" << std::endl;
	}

	if(StringContainsNone(source, "bcdfghjklmnpqrstvwxyz"))
	{
		std::cout << "String does not contain any consonants" << std::endl;
	}
	else
	{
		std::cout << "String contains consonants" << std::endl;
	}

	source = "aei12";

	if(StringContainsNone(source, "aeiou"))
	{
		std::cout << "String does not contain any vowels" << std::endl;
	}
	else
	{
		std::cout << "String contains vowels" << std::endl;
	}

	if(StringContainsNone(source, "0123456789"))
	{
		std::cout << "String does not contain any digits" << std::endl;
	}
	else
	{
		std::cout << "String contains digits" << std::endl;
	}

	return 0;
}

Output:
String contain vowels
String contains consonants
String contains vowels
String contains digits
Press any key to continue

Title: TokenizeString Description: This function will tokenize a string based on the characters in the 'delim' string. It will return a vector of all of the tokens. URL: Original design Source:
std::vector<std::string> TokenizeString(const std::string& str, const std::string& delim)
{
	using namespace std;
	vector<string> tokens;
	size_t p0 = 0, p1 = string::npos;
	while(p0 != string::npos)
	{
		p1 = str.find_first_of(delim, p0);
		if(p1 != p0)
		{
			string token = str.substr(p0, p1 - p0);
			tokens.push_back(token);
		}
		p0 = str.find_first_not_of(delim, p1);
	}
	return tokens;
}

Example:
#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> TokenizeString(const std::string& str, const std::string& delim)
{
	using namespace std;
	vector<string> tokens;
	size_t p0 = 0, p1 = string::npos;
	while(p0 != string::npos)
	{
		p1 = str.find_first_of(delim, p0);
		if(p1 != p0)
		{
			string token = str.substr(p0, p1 - p0);
			tokens.push_back(token);
		}
		p0 = str.find_first_not_of(delim, p1);
	}
	return tokens;
}

int main(int argc, char* argv[])
{
	std::string source = "This string will be tokenized by a vector of characters which are vowels";
	std::vector<std::string> tokens = TokenizeString(source, "aeiou");

	std::cout << source << std::endl;
	for(int x = 0; x < tokens.size(); x++)
	{
		std::cout << tokens[x] << std::endl;
	}

	std::cout << std::endl;

	source = "This.string.will; be tokenized, with  spaces and :puncutation!";
	tokens = TokenizeString(source, ",. :;!");
	std::cout << source << std::endl;
	for(int x = 0; x < tokens.size(); x++)
	{
		std::cout << tokens[x] << std::endl;
	}

	return 0;
}

Output:
This string will be tokenized by a vector of characters which are vowels
Th
s str
ng w
ll b
 t
k
n
z
d by
 v
ct
r
f ch
r
ct
rs wh
ch
r
 v
w
ls

This.string.will; be tokenized, with  spaces and :puncutation!
This
string
will
be
tokenized
with
spaces
and
puncutation
Press any key to continue

Title: FileToVector Description: This function will load a file and parse it based on the token into a vector. By default, it uses a newline. This function relies on the previous TokenizeString function. URL: None Source:
std::vector<std::string> FileToVector(const std::string& filename, const std::string& tokens = "\n")
{
	std::ifstream fin(filename.c_str());
	return TokenizeString(std::string((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>()), tokens);
}

Example:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

std::vector<std::string> TokenizeString(const std::string& str, const std::string& delim)
{
	using namespace std;
	vector<string> tokens;
	size_t p0 = 0, p1 = string::npos;
	while(p0 != string::npos)
	{
		p1 = str.find_first_of(delim, p0);
		if(p1 != p0)
		{
			string token = str.substr(p0, p1 - p0);
			tokens.push_back(token);
		}
		p0 = str.find_first_not_of(delim, p1);
	}
	return tokens;
}

std::vector<std::string> FileToVector(const std::string& filename, const std::string& tokens = "\n")
{
	std::ifstream fin(filename.c_str());
	return TokenizeString(std::string((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>()), tokens);
}

int main(int argc, char* argv[])
{
	// Load this file and tokenize it into a vector using 'a', 'e', 'i', 'o', and 'u'
	std::vector<std::string> tokens = FileToVector("main.cpp", "aeiou");
	for(int x = 0; x < tokens.size(); x++)
	{
		std::cout << tokens[x] << std::endl;
	}
	return 0;
}

Output:
<< Output >>

Title: lexer_merge_previous_append Description: This function will search a vector to see if any element is equal to 'token'. If it is, then that token will be removed from the vector, but it will be appended to the previous element in the vector. If there is a 'space' passed in, the contents of that variable will seperate the token from the end of the string of the previous element. You will have to call this multiple times for each 'token' you want. URL: None Source:
void lexer_merge_previous_append(std::vector<std::string>& source, const std::string& token, const std::string& space = "")
{
	std::vector<std::string>::iterator itr = std::find(source.begin(), source.end(), token);
	while(itr != source.end())
	{
		if(itr == source.begin())
			continue;
		std::string before = *(itr - 1);
		(itr - 1)->append(space);
		(itr - 1)->append(token);
		std::string after = *(itr - 1);
		source.erase(itr);
		itr = std::find(source.begin(), source.end(), token);
	}
}

Example:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

void lexer_merge_previous_append(std::vector<std::string>& source, const std::string& token, const std::string& space = "")
{
	std::vector<std::string>::iterator itr = std::find(source.begin(), source.end(), token);
	while(itr != source.end())
	{
		if(itr == source.begin())
			continue;
		std::string before = *(itr - 1);
		(itr - 1)->append(space);
		(itr - 1)->append(token);
		std::string after = *(itr - 1);
		source.erase(itr);
		itr = std::find(source.begin(), source.end(), token);
	}
}

int main(int argc, char* argv[])
{
	std::vector<std::string> source;
	source.push_back("int");
	source.push_back("*");
	source.push_back("var1");
	source.push_back(",");
	source.push_back("char");
	source.push_back("*");
	source.push_back("var2");

	// Show the original elemnts of the vector
	for(int x = 0; x < source.size(); x++)
	{
		std::cout << source[x] << " ";
	}
	std::cout << std::endl << std::endl;

	// Merge all '*' at the end of the previous element
	lexer_merge_previous_append(source, "*");

	// Show the new elemnts of the vector
	for(int x = 0; x < source.size(); x++)
	{
		std::cout << source[x] << " ";
	}
	std::cout << std::endl << std::endl;

	return 0;
}

Output:
int * var1 , char * var2

int* var1 , char* var2

Press any key to continue

Title: lexer_merge_previous_prepend Description: This function will search a vector to see if any element is equal to 'token'. If it is, then that token will be removed from the vector, but it will be prepended to the previous element in the vector. If there is a 'space' passed in, the contents of that variable will seperate the token from the start of the string of the previous element. URL: None Source:
void lexer_merge_previous_prepend(std::vector<std::string>& source, const std::string& token, const std::string& space = "")
{
	std::vector<std::string>::iterator itr = std::find(source.begin(), source.end(), token);
	while(itr != source.end())
	{
		if(itr == source.begin())
			continue;
		std::string newStr = token;
		newStr += space;
		newStr += (*(itr - 1));
		(*(itr - 1)) = newStr;
		source.erase(itr);
		itr = std::find(source.begin(), source.end(), token);
	}
}

Example:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

void lexer_merge_previous_prepend(std::vector<std::string>& source, const std::string& token, const std::string& space = "")
{
	std::vector<std::string>::iterator itr = std::find(source.begin(), source.end(), token);
	while(itr != source.end())
	{
		if(itr == source.begin())
			continue;
		std::string newStr = token;
		newStr += space;
		newStr += (*(itr - 1));
		(*(itr - 1)) = newStr;
		source.erase(itr);
		itr = std::find(source.begin(), source.end(), token);
	}
}

int main(int argc, char* argv[])
{
	std::vector<std::string> source;
	source.push_back("int");
	source.push_back("*");
	source.push_back("var1");
	source.push_back(",");
	source.push_back("char");
	source.push_back("*");
	source.push_back("var2");

	// Show the original elemnts of the vector
	for(int x = 0; x < source.size(); x++)
	{
		std::cout << source[x] << " ";
	}
	std::cout << std::endl << std::endl;

	// Merge all '*' at the start of the previous element
	lexer_merge_previous_prepend(source, "*");

	// Show the new elemnts of the vector
	for(int x = 0; x < source.size(); x++)
	{
		std::cout << source[x] << " ";
	}
	std::cout << std::endl << std::endl;

	return 0;
}

Output:
int * var1 , char * var2

*int var1 , *char var2

Press any key to continue

Title: lexer_merge_next_append Description: This function will search a vector to see if any element is equal to 'token'. If it is, then that token will be removed from the vector, but it will be appended to the next element in the vector. If there is a 'space' passed in, the contents of that variable will seperate the token from the end of the string of the next element. URL: None Source:
void lexer_merge_next_append(std::vector<std::string>& source, const std::string& token, const std::string& space = "")
{
	std::vector<std::string>::iterator itr = std::find(source.begin(), source.end(), token);
	while(itr < (source.end() - 1))
	{
		(itr + 1)->append(space);
		(itr + 1)->append(token);
		source.erase(itr);
		itr = std::find(source.begin(), source.end(), token);
	}
}

Example:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

void lexer_merge_next_append(std::vector<std::string>& source, const std::string& token, const std::string& space = "")
{
	std::vector<std::string>::iterator itr = std::find(source.begin(), source.end(), token);
	while(itr < (source.end() - 1))
	{
		(itr + 1)->append(space);
		(itr + 1)->append(token);
		source.erase(itr);
		itr = std::find(source.begin(), source.end(), token);
	}
}

int main(int argc, char* argv[])
{
	std::vector<std::string> source;
	source.push_back("int");
	source.push_back("*");
	source.push_back("var1");
	source.push_back(",");
	source.push_back("char");
	source.push_back("*");
	source.push_back("var2");

	// Show the original elemnts of the vector
	for(int x = 0; x < source.size(); x++)
	{
		std::cout << source[x] << " ";
	}
	std::cout << std::endl << std::endl;

	// Merge all '*' at the end of the next element
	lexer_merge_next_append(source, "*");

	// Show the new elemnts of the vector
	for(int x = 0; x < source.size(); x++)
	{
		std::cout << source[x] << " ";
	}
	std::cout << std::endl << std::endl;

	return 0;
}

Output:
int * var1 , char * var2

int var1* , char var2*

Press any key to continue

Title: lexer_merge_next_prepend Description: This function will search a vector to see if any element is equal to 'token'. If it is, then that token will be removed from the vector, but it will be prepended to the next element in the vector. If there is a 'space' passed in, the contents of that variable will seperate the token from the beginning of the string of the next element. URL: None Source:
void lexer_merge_next_prepend(std::vector<std::string>& source, const std::string& token, const std::string& space = "")
{
	std::vector<std::string>::iterator itr = std::find(source.begin(), source.end(), token);
	while(itr < (source.end() - 1))
	{
		std::string newStr = token;
		newStr += space;
		newStr += (*(itr + 1));
		(*(itr + 1)) = newStr;
		source.erase(itr);
		itr = std::find(source.begin(), source.end(), token);
	}
}

Example:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

void lexer_merge_next_prepend(std::vector<std::string>& source, const std::string& token, const std::string& space = "")
{
	std::vector<std::string>::iterator itr = std::find(source.begin(), source.end(), token);
	while(itr < (source.end() - 1))
	{
		std::string newStr = token;
		newStr += space;
		newStr += (*(itr + 1));
		(*(itr + 1)) = newStr;
		source.erase(itr);
		itr = std::find(source.begin(), source.end(), token);
	}
}

int main(int argc, char* argv[])
{
	std::vector<std::string> source;
	source.push_back("int");
	source.push_back("*");
	source.push_back("var1");
	source.push_back(",");
	source.push_back("char");
	source.push_back("*");
	source.push_back("var2");

	// Show the original elemnts of the vector
	for(int x = 0; x < source.size(); x++)
	{
		std::cout << source[x] << " ";
	}
	std::cout << std::endl << std::endl;

	// Merge all '*' at the end of the next element
	lexer_merge_next_prepend(source, "*");

	// Show the new elemnts of the vector
	for(int x = 0; x < source.size(); x++)
	{
		std::cout << source[x] << " ";
	}
	std::cout << std::endl << std::endl;

	return 0;
}

Output:
int * var1 , char * var2

int *var1 , char *var2

Press any key to continue

Title: RemoveAdjacentRepetitions Description: This function will use the unique algorithm to remove adjacent repetitions in a vector. URL: Original design Source:
template <class type>
void RemoveAdjacentRepetitions(std::vector<type> &vec)
{
	vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}

Example:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

template <class type>
void RemoveAdjacentRepetitions(std::vector<type> &vec)
{
	vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}

int main(int argc, char* argv[])
{
	std::vector<int> intList;
	for(int x = 0; x < 10; x++)
		intList.push_back(x);
	for(int x = 0; x < 10; x+=2)
		intList.push_back(x);

	// For this example, we will sort to repitions are next to each other
	sort(intList.begin(), intList.end());

	for(int x = 0; x <intList.size(); x++)
		std::cout << intList[x] << ' ';
	std::cout << std::endl << std::endl;

	// Remove any adjacent repeating elements
	RemoveAdjacentRepetitions(intList);

	for(int x = 0; x <intList.size(); x++)
		std::cout << intList[x] << ' ';
	std::cout << std::endl << std::endl;

	return 0;
}

Output:
0 0 1 2 2 3 4 4 5 6 6 7 8 8 9

0 1 2 3 4 5 6 7 8 9

Press any key to continue

Title: ToString Description: This function will take any data type that has the extraction operator defined and convert it to a string. It will work for all basics data types URL: None Source:
template <class type>
std::string ToString(type source)
{
	using namespace std;
	stringstream output;
	output << source;
	return output.str();
}

Example:
#include <iostream>
#include <string>
#include <sstream>

template <class type>
std::string ToString(type source)
{
	using namespace std;
	stringstream output;
	output << source;
	return output.str();
}

int main(int argc, char* argv[])
{
	std::string myStr1 = ToString(5);
	std::cout << myStr1 << std::endl;

	std::string myStr2 = ToString(3.1415);
	std::cout << myStr2 << std::endl;

	std::string myStr3 = ToString('a');
	std::cout << myStr3 << std::endl;
	return 0;
}

Output:
5
3.1415
a
Press any key to continue

Title: StringToUpper Description: This function will take a string and convert it to all upper case. URL: Original design Source:
void StringToUpper(std::string& source)
{
	std::transform(source.begin(), source.end(), source.begin(), toupper);
}

Example:
#include <iostream>
#include <string>
#include <algorithm>

void StringToUpper(std::string& source)
{
	std::transform(source.begin(), source.end(), source.begin(), toupper);
}

int main(int argc, char* argv[])
{
	using namespace std;
	string source = "ThIs Is A MiXeD CaSe StRiNg";
	cout << source << endl;
	StringToUpper(source);
	cout << source << endl;
	return 0;
}

Output:
ThIs Is A MiXeD CaSe StRiNg
THIS IS A MIXED CASE STRING
Press any key to continue

Title: StringToLower Description: This function will take a string and make it all lowercase URL: Original design Source:
void StringToLower(std::string& source)
{
	std::transform(source.begin(), source.end(), source.begin(), tolower);
}

Example:
#include <iostream>
#include <string>
#include <algorithm>

void StringToLower(std::string& source)
{
	std::transform(source.begin(), source.end(), source.begin(), tolower);
}

int main(int argc, char* argv[])
{
	using namespace std;
	string source = "ThIs Is A MiXeD CaSe StRiNg";
	cout << source << endl;
	StringToLower(source);
	cout << source << endl;
	return 0;
}

Output:
ThIs Is A MiXeD CaSe StRiNg
this is a mixed case string
Press any key to continue

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By Manuel Berger
      Hello fellow devs!
      Once again I started working on an 2D adventure game and right now I'm doing the character-movement/animation. I'm not a big math guy and I was happy about my solution, but soon I realized that it's flawed.
      My player has 5 walking-animations, mirrored for the left side: up, upright, right, downright, down. With the atan2 function I get the angle between player and destination. To get an index from 0 to 4, I divide PI by 5 and see how many times it goes into the player-destination angle.

      In Pseudo-Code:
      angle = atan2(destination.x - player.x, destination.y - player.y) //swapped y and x to get mirrored angle around the y axis
      index = (int) (angle / (PI / 5));
      PlayAnimation(index); //0 = up, 1 = up_right, 2 = right, 3 = down_right, 4 = down

      Besides the fact that when angle is equal to PI it produces an index of 5, this works like a charm. Or at least I thought so at first. When I tested it, I realized that the up and down animation is playing more often than the others, which is pretty logical, since they have double the angle.

      What I'm trying to achieve is something like this, but with equal angles, so that up and down has the same range as all other directions.

      I can't get my head around it. Any suggestions? Is the whole approach doomed?

      Thank you in advance for any input!
       
    • By devbyskc
      Hi Everyone,
      Like most here, I'm a newbie but have been dabbling with game development for a few years. I am currently working full-time overseas and learning the craft in my spare time. It's been a long but highly rewarding adventure. Much of my time has been spent working through tutorials. In all of them, as well as my own attempts at development, I used the audio files supplied by the tutorial author, or obtained from one of the numerous sites online. I am working solo, and will be for a while, so I don't want to get too wrapped up with any one skill set. Regarding audio, the files I've found and used are good for what I was doing at the time. However I would now like to try my hand at customizing the audio more. My game engine of choice is Unity and it has an audio mixer built in that I have experimented with following their tutorials. I have obtained a great book called Game Audio Development with Unity 5.x that I am working through. Half way through the book it introduces using FMOD to supplement the Unity Audio Mixer. Later in the book, the author introduces Reaper (a very popular DAW) as an external program to compose and mix music to be integrated with Unity. I did some research on DAWs and quickly became overwhelmed. Much of what I found was geared toward professional sound engineers and sound designers. I am in no way trying or even thinking about getting to that level. All I want to be able to do is take a music file, and tweak it some to get the sound I want for my game. I've played with Audacity as well, but it didn't seem to fit the bill. So that is why I am looking at a better quality DAW. Since being solo, I am also under a budget contraint. So of all the DAW software out there, I am considering Reaper or Presonus Studio One due to their pricing. My question is, is investing the time to learn about using a DAW to tweak a sound file worth it? Are there any solo developers currently using a DAW as part of their overall workflow? If so, which one? I've also come across Fabric which is a Unity plug-in that enhances the built-in audio mixer. Would that be a better alternative?
      I know this is long, and maybe I haven't communicated well in trying to be brief. But any advice from the gurus/vets would be greatly appreciated. I've leaned so much and had a lot of fun in the process. BTW, I am also a senior citizen (I cut my programming teeth back using punch cards and Structured Basic when it first came out). If anyone needs more clarification of what I am trying to accomplish please let me know.  Thanks in advance for any assistance/advice.
    • By Yosef BenSadon
      Hi , I was considering this start up http://adshir.com/, for investment and i would like a little bit of feedback on what the developers community think about the technology.
      So far what they have is a demo that runs in real time on a Tablet at over 60FPS, it runs locally on the  integrated GPU of the i7 . They have a 20 000 triangles  dinosaur that looks impressive,  better than anything i saw on a mobile device, with reflections and shadows looking very close to what they would look in the real world. They achieved this thanks to a  new algorithm of a rendering technique called Path tracing/Ray tracing, that  is very demanding and so far it is done mostly for static images.
      From what i checked around there is no real option for real time ray tracing (60 FPS on consumer devices). There was imagination technologies that were supposed to release a chip that supports real time ray tracing, but i did not found they had a product in the market or even if the technology is finished as their last demo  i found was with a PC.  The other one is OTOY with their brigade engine that is still not released and if i understand well is more a cloud solution than in hardware solution .
      Would there  be a sizable  interest in the developers community in having such a product as a plug-in for existing game engines?  How important  is Ray tracing to the  future of high end real time graphics?
    • By bryandalo
      Good day,

      I just wanted to share our casual game that is available for android.

      Description: Fight your way from the ravenous plant monster for survival through flips. The rules are simple, drag and release your phone screen. Improve your skills and show it to your friends with the games quirky ranks. Select an array of characters using the orb you acquire throughout the game.

      Download: https://play.google.com/store/apps/details?id=com.HellmodeGames.FlipEscape&hl=en
       
      Trailer: 
       
    • By khawk
      Watch the latest from Unity.
       
  • Advertisement