2016-02-11 43 views
0

這是一個跟進my question yesterday如何將一個整數附加到一個字符串?

我用一個函數來下載文件:

void downloadFile(const char* url, const char* fname, const char* id) { 
    //.. 
} 

這就是所謂的喜歡:

downloadFile( 「http://servera.com/file.txt」, 「/user/tmp/file.txt」,「/家庭/用戶/下載/ XXXX「);

這正常工作與固定id如圖所示,但我需要xxxx用隨機數代替:

srand(time(NULL)); 
int rdn = rand(); 

如果我嘗試:

downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt", "/home/user/Download/" + rdn); 

我得到

error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]

那麼如何將rdn附加到字符串"/home/user/Download/"?例如,如果rdm == 123456789,我想通過"/home/user/Download/123456789"該函數。

+4

有'sprintf'但** **請使用'的std :: string' /'的std :: to_string'。 – leemes

+0

你希望用'「/ home/user/Download /」+ rdn'實現什麼? –

+3

我特別對downvote和close-votes感到困惑。對我來說,這似乎是一個程序員,它來自於可以使用'+'將事物串聯到一個字符串的背景,例如在Java中。 @barakmanos我很確定他試圖將數字(作爲字符串)連接到前綴。 –

回答

3

如果使用C++ 11,你可以做

std::string download_location = "/home/user/Download/" + std::to_string(rdn) 
downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt", download_location.c_str()); 

更妙的是使用char *和使用字符串做掉無處不在。用char *引入錯誤太容易了。

或者,你也可以使用stringstream進行泛型和高效的字符串連接/格式化。

#include <sstream> 
... 

stringstream download_location_stream; 
download_location_stream << "/home/user/Download" << rdn; 

downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt", 
      download_location_stream.str().c_str()); 
+0

當我嘗試這個時,我得到的錯誤to_string不在std中。 – Rocket

+0

如果你做了很多字符串連接,你可能要考慮重載'operator +'來幫助你。 '/ **附加有字符串指明分數T */ 模板 的std :: string操作者+字符串(常量的std :: string&一個,常量T&B) { 返回一個+的std :: to_string(b)中; }'' /***在前面加上一個字符串指明分數T */ 模板 的std :: string操作者+(常量T&一個,常量的std :: string&B) { 返回的std :: to_string(字符串a)+ b; }'然後'std :: string(「/ some/dir /」)+ rnd'應該可以工作。 (抱歉格式不對,無法回答已關閉的問題。) –

+0

@Rocket您可能不使用C++ 11編譯器或禁用某些相關功能。沒關係,我已經添加了另一種適用於較舊編譯器的方法。 – Sorin

3

爲@leemes說,你可以使用的sprintf:

char str[100]; 
sprintf(str,"/home/user/Download/%d",rdn); 
downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt", str); 
+2

在這裏可能更好地使用'snprintf()'而不是普通的'sprintf()'。 –

+2

對於一切聖潔的愛~~恨鼻惡魔,請始終使用'snprintf'。 –

+0

你能解釋一下snprintf和sprintf之間的區別嗎?爲什麼有關於使用另一個的問題?你如何使用snprintf?這個解決方案對我來說非常棒! – Rocket

相關問題