2012-02-16 107 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