2012-02-16 101 views
2

我必须将增加的ID作为关键字保存到levelDB数据库中。所以我得到(以及我必须给levelDB)是一个字符串。增加字符串中的数字

问题:有没有一种优雅的方式来增加保存在字符串中的数字?

例子:

std::string key = "123"; 
[..fancy code snipped to increase key by 1..] 
std::cout << key << std::endl; // yields 124 

干杯! PS:宁愿留在标准编译中,即没有C++ 11。

+0

你确定的值不是124? – 2012-02-16 10:30:54

+0

@izomorphius:typo ..谢谢..它是从123到124 – ezdazuzena 2012-02-16 10:31:31

+0

所以你的关键实际上是123,而不是你的价值?你的旧密钥会发生什么? – Kiril 2012-02-16 10:37:05

回答

3
#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; 

您也可以使用C风格的铸造它:

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; 
+0

它可能是itoa不是标准的C++ ..看起来它不支持g ++ – ezdazuzena 2012-02-16 11:22:11

+0

hmmm我99%肯定它是由g ++支持的。尝试包括cstdlib – 2012-02-16 11:24:18

+0

nope ..不起作用 – ezdazuzena 2012-02-16 11:25:35

1

也许是这样的:

std::string key = "123"; 
std::stringstream out; 
out << (atoi(key.c_str()) + 1); 
key = out.str(); 
0

代码:

istringstream iss(key); 
int ikey; 
iss >> ikey; 
ostringstream oss; 
oss << (ikey+1); 
key = oss.str(); 
2

你总是可以写一个小程序来办基地10算术,但最简单的解决方案通常是为了保持号码作为int(或其他一些整数类型),并根据需要将其转换为字符串。

0

啊,这是真的,性LevelDB确实需要在字符串,它可以返回一个字符串,Slice结构还具有构造函数与数据的不透明数组:

// Create a slice that refers to data[0,n-1]. 
Slice(const char* data, size_t n) 

当你一键搞定Slice你仍然有char*其中的数据,所以你真的不与琴弦打扰:

// Return a pointer to the beginning of the referenced data 
const char* data() const { return data_; } 

如果你的整个目标是有一个整数的关键,那么就你的整数转换为char *和商店它leveldb,像这样:

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)); 

无需麻烦的和昂贵的琴弦......

+0

错误:从'char *'转换为'int'失去精度:((在'key =(char *)(((int)key)+1);') – ezdazuzena 2012-02-16 11:26:43

+0

@ezdazuzena我不是得到错误,这里是一个gcc-4.3.4编译版本:http://ideone.com/W3NQ2我也在VS 2010中编译了相同的代码(包括32位和64位平台)。编译它? – Kiril 2012-02-16 14:30:35

+0

gcc版本4.5.2(Ubuntu/Linaro 4.5.2-8ubuntu4) – ezdazuzena 2012-02-16 15:07:16