2012-08-02 72 views
0

此示例代碼是否有效?字符串作爲參數(C++)

std::string x ="There are"; 
int butterflies = 5; 
//the following function expects a string passed as a parameter 
number(x + butterflies + "butterflies"); 

這裏的主要問題是我是否可以只使用+運算符作爲字符串的一部分傳遞整數。但如果有任何其他錯誤,請讓我知道:)

+2

'這是示例代碼有效' - 什麼是你的編譯器告訴你? – mah 2012-08-02 01:03:37

回答

1

一個安全的方式給你的整數轉換爲字符串將是一個摘錄如下:

#include <string> 
#include <sstream> 

std::string intToString(int x) 
{ 
    std::string ret; 
    std::stringstream ss; 
    ss << x; 
    ss >> ret; 
    return ret; 
} 

您當前的例子也不會出於上述原因,工作。

4

C++不會自動轉換爲這樣的字符串。你需要創建一個字符串流或者使用類似boost詞法轉換的東西。

1

不,它不會工作。 C++它不是無類型語言。所以它不能自動將整數轉換爲字符串。使用類似strtol,stringstream等。

1

C++比C++更多,但是sprintf(與printf類似,但將結果放入字符串中)在此處很有用。

2

您可以使用字符串流用於此目的的那樣:

#include <iostream> 
#include <sstream> 
using namespace std; 

int main() 
{ 
    stringstream st; 
    string str; 

    st << 1 << " " << 2 << " " << "And this is string" << endl; 
    str = st.str(); 

    cout << str; 
    return 0; 
}