包括在 <sstream> Xcode 9.2 中不起作用

include <sstream> not working in Xcode 9.2

本文关键字:不起作用 Xcode sstream lt 包括 gt      更新时间:2023-10-16

我现在正在学习 c++,并且在尝试连接字符串和数字时遇到了问题sstream因为它对我不起作用。

我得到的错误是:

二进制表达式的操作数无效("basic_string,标准::__1::分配器>"和"int"(。

代码如下:

#include <iostream>
#include <sstream>
using namespace std;
int main() {
string name = "Jane";
int age = 28;
string info = "Name: " + name + "; age:" + age;
cout >> info >> endl;
return 0;
}

您的问题不在于sstream,而是与此处的这一行有关:

string info = "Name: " + name + "; age:" + age;

一切看起来都很好,直到"; age:" + age.不能添加stringint。您可以使用std::to_stringint转换为string

string info = "Name: " + name + "; age:" + to_string(age);

to_string是在 C++11 中添加的,但如果由于某种原因你不能使用 C++11,你可以使用字符串流自己定义这个函数:

template <typename T>
string to_string(const T &thing) {
std::ostringstream oss;
oss << thing;
return oss.str();
}

另请注意,您在cout上使用提取运算符。你可能的意思是:

cout << info << endl;

要使用字符串流创建一个连接字符串和其他类型的新字符串,您需要如下所示的内容:

int meaning = 42;
ostringstream os;
os << "The meaning of life is " << meaning;
string s = os.str();