字符串作为参数(C++)

问题描述:

此示例代码是否有效?字符串作为参数(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

一个安全的方式给你的整数转换为字符串将是一个摘录如下:

#include <string> 
#include <sstream> 

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

您当前的例子也不会出于上述原因,工作。

C++不会自动转换为这样的字符串。你需要创建一个字符串流或者使用类似boost词法转换的东西。

不,它不会工作。 C++它不是无类型语言。所以它不能自动将整数转换为字符串。使用类似strtol,stringstream等。

C++比C++更多,但是sprintf(与printf类似,但将结果放入字符串中)在此处很有用。

您可以使用字符串流用于此目的的那样:

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