2017-03-08 116 views
-1

我必須連接整數與字符串如下,用戶將輸入一個數字,例如, 1,它會被放在字符串是這樣的:連接整數與字符串格式字符串

std::remove("C:/Users/pcname/Desktop/files/1.txt"); 

如果用戶輸入2,它就像

std::remove("C:/Users/pcname/Desktop/files/2.txt"); 

這是非常基本的,但我有這個問題,我試圖用operator+與這但是沒有奏效。

+0

更具體。展示「不起作用」的問題代碼。 – tambre

+0

發帖之前請先搜索StackOverflow。我推薦關鍵字「stackoverflow c + +連接字符串整數」。 –

回答

1

可以使用std::to_string整數轉換爲std::string,然後使用串聯

int file_num = 1; 
std::remove("C:/Users/pcname/Desktop/files/" + std::to_string(file_num) + ".txt"); 

否則試圖做類似

"C:/Users/pcname/Desktop/files/" + file_num 

其實就是做pointer arithmetic,不會產生串你認爲它會

+0

[錯誤]'to_string'不是'std'的成員 – Sikander

+0

並且萬一你不能使用> C++ 11,'boost :: lexical_cast' – Ceros

+0

請詳細說明我無法獲得第二點提示:: lexical_cast – Sikander