mirror of
https://github.com/TerryCavanagh/VVVVVV.git
synced 2025-01-09 10:29:45 +01:00
Refactor ss_toi() to not use stringstreams
Apart from the std::string, this function no longer uses the STL. ss_toi() is a simple function - it converts the input into an int, taking as many digits as possible until it reaches a non-digit character, at which point it stops. It's trivial to implement this without the STL. I could've used Int() here, but that would've required copying the string to a temporary buffer to insert a null-terminator (we can't just use a pointer-and-length data type either, the string functions don't operate like that - one disadvantage of C strings!). Instead, I decided to implement my own conversion to int here, because I don't think the way we humans write our Arabic numerals is going to change anytime soon. Also, the std::string input is now passed by const reference, instead of making a copy - cutting down on unnecessary memory operations.
This commit is contained in:
parent
e1ae25b29b
commit
46b0257cf1
2 changed files with 35 additions and 6 deletions
|
@ -36,12 +36,41 @@ static const char* GCChar(const SDL_GameControllerButton button)
|
|||
}
|
||||
}
|
||||
|
||||
int ss_toi( std::string _s )
|
||||
int ss_toi(const std::string& str)
|
||||
{
|
||||
std::istringstream i(_s);
|
||||
int x = 0;
|
||||
i >> x;
|
||||
return x;
|
||||
int retval = 0;
|
||||
int place = 1;
|
||||
bool negative = false;
|
||||
const int radix = 10;
|
||||
|
||||
for (size_t i = 0; i < str.size(); ++i)
|
||||
{
|
||||
const char chr = str[i];
|
||||
|
||||
if (i == 0 && chr == '-')
|
||||
{
|
||||
negative = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (SDL_isdigit(chr))
|
||||
{
|
||||
retval *= place;
|
||||
retval += chr - '0';
|
||||
place *= radix;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (negative)
|
||||
{
|
||||
return -retval;
|
||||
}
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
std::vector<std::string> split( const std::string &s, char delim, std::vector<std::string> &elems )
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
int ss_toi(std::string _s);
|
||||
int ss_toi(const std::string& str);
|
||||
|
||||
std::vector<std::string> split(const std::string &s, char delim, std::vector<std::string> &elems);
|
||||
|
||||
|
|
Loading…
Reference in a new issue