std :: stringstream“str”什么都没有回来?

时间:2011-12-11 21:02:47

标签: c++ string templates

我遇到std::stringstream时遇到问题。我的功能如下所示,绝对没有任何回报。即使在模板函数之外尝试字符串流时,在调用.str()时它仍然不返回任何内容。

template < class T > std::string toString( const T &t )
{
    std::stringstream temp;
    temp << t;
    std::cout << temp.str() << std::endl;
    return temp.str();
}

std::string test = "test" + toString( 1 );
std::cout << test << std::endl;
std::stringstream stream;
stream << "test" << 1;
std::cout << stream.str() << std::endl;

这两个输出只是“测试”

固定

必须从我的预处理器宏中删除_GLIBCXX_DEBUG_GLIBCXX_DEBUG_PEDANTIC

2 个答案:

答案 0 :(得分:1)

尝试使用ostringstream代替stringstream

==更新==

我用GCC 4.6.1编译了你的代码,它按原样运行:

#include <iostream>
#include <sstream>

using namespace std;

template < class T > std::string toString( const T &t )
{
    std::stringstream temp;
    temp << t;
    std::cout << temp.str() << std::endl;
    return temp.str();
}

int main()
{
  std::string test = "test" + toString( 1 );
  std::cout << test << std::endl;
  std::stringstream stream;
  stream << "test" << 1;
  std::cout << stream.str() << std::endl;
  return 0;
}

输出:

1
test1
test1

答案 1 :(得分:1)

#include <iostream>
#include <sstream>
#include <string>

template < class T > std::string toString( const T &t )
{
    std::stringstream temp;
    temp << t;
    std::cout << temp.str() << std::endl;
    return temp.str();
}

int main(){
    std::string test = "test" + toString( 1 );
    std::cout << test << std::endl;
    std::stringstream stream;
    stream << "test" << 1;
    std::cout << stream.str() << std::endl;
}

输出

1
test1
test1

对于Clang 3.1,GCC 4.4.5和MSVC 10,我的问题出在其他地方。请在新项目中尝试上面的代码,看看问题是否仍然存在。如果没有,@ Industrial-antidepressant的建议听起来很现实,即你在某个地方有更好的匹配过载。

相关问题