increase number in string
سؤال
I have to save an increasing ID as key into a levelDB database. So what I get (and what I have to give to levelDB) is a string.
Question: Is there an elegant way to increase a number saved in a string?
Example:
std::string key = "123";
[..fancy code snipped to increase key by 1..]
std::cout << key << std::endl; // yields 124
Cheers!
PS: Would prefer to stay with standard compilation, i.e. no C++11.
المحلول
#include <sstream>
std::string key = "123";
std::istringstream in(key);
int int_key;
in >> int_key;
int_key++;
std::ostringstream out;
out << int_key;
key = out.str();
std::cout << key << std::endl;
You can also do it using c style casting:
std::string key = "123";
int int_key = atoi(key.c_str());
int_key++;
char key_char[20];
itoa(int_key, key_char, 10);
key = key_char;
cout << key << endl;
نصائح أخرى
You could always write a small routine to do base 10 arithmetic, but the simplest solution is usually to keep the number as an int
(or some other integral type), and convert that into a string as needed.
Perhaps something like this:
std::string key = "123";
std::stringstream out;
out << (atoi(key.c_str()) + 1);
key = out.str();
Code:
istringstream iss(key);
int ikey;
iss >> ikey;
ostringstream oss;
oss << (ikey+1);
key = oss.str();
Ah, it's true that leveldb does take in strings and it can return a string, but the Slice
structure also has a constructor with an opaque array of data:
// Create a slice that refers to data[0,n-1].
Slice(const char* data, size_t n)
When you get a key Slice
you still have a char*
as the data, so you don't really have to bother with the strings:
// Return a pointer to the beginning of the referenced data
const char* data() const { return data_; }
If your entire goal is to have a an integer as the key, then just convert your integer to a char* and store it in leveldb
, like so:
int oldKey = 123;
char key[8];
memset(key, 0, 8);
*(int*)(&key) = oldKey;
*(int*)(&key) += 1;
// key is now 124
// want to put it back in a slice?
Slice s(key, sizeof(int));
No need for pesky and expensive strings...