【问题标题】:size_t convert/cast to string in C++ [duplicate]size_t 在 C++ 中转换/转换为字符串 [重复]
【发布时间】:2012-05-17 14:43:21
【问题描述】:

可能重复:
How to convert a number to string and vice versa in C++

如何在 C++ 中将整数值转换为 string

这是我尝试过的:

for(size_t i = 0;vecServiceList.size()>i;i++)
{
    if ( ! vecServiceList[i].empty() )
    {
        string sService = "\t" + i +". "+  vecServiceList[i] ;
    }
}

这是错误:

invalid operands of types 'const char*' and 'const char [3]' to binary 'operator+'

【问题讨论】:

  • @CodyGray,正在寻找那个,谢谢。
  • 我的第一个猜测是你需要一些东西,例如boost:format("%lu") % i,但是错误是什么?
  • std::to_string((int)var)
  • @7heo.tk 我看不出这与 /at all / 有什么关系。此外,标记的副本完美地提到了所有整数类型,所以这不是问题。
  • @sehe 我的错,我发现这个问题正在搜索 size_t atoi 的安全替代品。我没有费心去检查问题是用“to”还是“from”写的。

标签: c++ string


【解决方案1】:

你可以使用字符串流:

#include <sstream>

...


for (size_t i = 0; ... ; ...)
{
    std::stringstream ss;

    ss << "\t" << i << vecServiceList[i];

    std::string sService = ss.str();

    // do what you want with sService
}

【讨论】:

    猜你喜欢
    • 2016-03-06
    • 2014-01-08
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 2013-10-29
    相关资源
    最近更新 更多