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

String as a parameter (C++)

本文关键字:C++ 参数 字符串      更新时间:2023-10-16

此示例代码有效吗?

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

这里的主要问题是,我是否可以使用+运算符将整数作为字符串的一部分进行传递。但如果还有任何其他错误,请告诉我:)

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

您可以将字符串流用于以下目的:

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

将整数转换为字符串的一种安全方法是摘录如下:

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

由于上述原因,您当前的示例将不起作用。

不,它不起作用。C++不是一种无类型的语言。所以它不能自动将integer强制转换为字符串。使用strtol、stringstream等。

C比C++多,但sprintf(类似于printf,但将结果放在字符串中)在这里会很有用。