您好,下面是我的职能:
string Employee::get_print(void) {
string out_string;
stringstream ss;
ss << e_id << " " << type << endl;
out_string = ss.str();
return out_string;
}
e_id
和 type
是 int
它们包含来自 Employee 类的值。但是,当我将它们传递到 stringstream 时,当我尝试输出时,它们只会清除字符串。但是如果我没有 int
在ss << "Some text" << endl;
这个输出很好。我做错了什么=S
//编辑
好的; 这是调用代码:
tmp = cur->get_print();
其中 tmp 是一个字符串,cur 是一个 Employee 对象。
这段代码...
stringstream out;
out << "Test " << e_id << " " << e_type;
return out.str();
重新运行“测试”,仅此而已。如果我取出"Test " <<
我返回的字符串是“”
我在 Mac OS/X 10.6.2 上使用 GCC 4.2,如果这有什么不同的话。
最佳答案
我也无法重现这个错误。如前所述,不要包含 endl
,因为这实际上附加了一个 \n
并且应该刷新写入缓冲区。对于这种用途,它是完全没有必要的,实际上可能会导致不良结果......但是,您编辑/更新中的代码对我来说工作得很好。
int main(int argc, char* argv[])
{
int e_id = 5;
int e_type = 123456;
stringstream out;
out << "Test " << e_id << " " << e_type;
cout << out.str();
return 0;
}
产生:
Test 5 123456
我的建议是仔细检查 e_id
和 e_type
是否真的只是原生 int
。
为了进一步测试,您可能需要强制转换值以查看它是否有帮助:
out << "Test " << (int)e_id << " " << (int)e_type;
由于我无法重现此错误,恐怕我无法提供更多帮助。但祝你好运!
关于C++ Stringstream int 到 string 但返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2478648/