如何使用格式说明符创建字符串?

时间:2012-06-11 09:49:16

标签: c++ string

我想创建一个以字符串作为参数的公共api,并将此字符串放在我已在该Api中的另一个字符串中放置格式指定符的位置。

e.g. string PrintMyMessage( const string& currentValAsString)
     {
          string s1("Current value is %s",currentValAsString);
          return s1;
     }

目前我收到了以下构建错误。

1>d:\extra\creatingstrwithspecifier\creatingstrwithspecifier\main.cxx(8): error C2664: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &,unsigned int,unsigned int)' : cannot convert parameter 2 from 'const std::string' to 'unsigned int'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Ax=std::allocator<char>
1>          ]
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

我只是想知道什么是完成这项任务的更好方法。

4 个答案:

答案 0 :(得分:1)

正如this rather similar question中所述,您可以使用Boost Format Library。例如:

std::string PrintMyMessage( const string& currentValAsString )
{
  boost::format fmt = boost::format("Current value is %s") % currentValAsString; 
  // note that you could directly use cout:
  //std::cout << boost::format("Current value is %s") % currentValAsString;
  return fmt.str();
}

在其他问题的答案中,您还可以找到其他方法,例如:使用stringstreams,snprintf或字符串连接。

这是一个完整的通用示例:

#include <string>
#include <iostream>
#include <boost/format.hpp>

std::string greet(std::string const & someone) {
    boost::format fmt = boost::format("Hello %s!") % someone;
    return fmt.str();
}

int main() {
    std::cout << greet("World") << "\n";
}

或者,如果你不能或不想使用Boost:

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>

std::string greet(std::string const & someone) {
    const char fmt[] = "Hello %s!";
    std::vector<char> buf(sizeof(fmt)+someone.length());
    std::snprintf(&buf[0], buf.size(), fmt, someone.c_str());
    return &buf[0];
}

int main() {
    std::cout << greet("World") << "\n";
}

两个示例都产生以下输出:

$ g++ test.cc && ./a.out
Hello World!

答案 1 :(得分:0)

string PrintMyMessage( const string& currentValAsString)
{
    char buff[100];
    sprintf(buff, "Current value is %s", currentValAsString.c_str());

    return buff;
}

答案 2 :(得分:0)

string PrintMyMessage(const char* fmt, ...)
{
    char buf[1024];
    sprintf(buf, "Current value is ");

    va_list ap;
    va_start(ap, fmt);
    vsprintf(buf + strlen(buf), fmt, ap);

    return buf;
}

string str = PrintMyMessage("Port is %d, IP is :%s", 80, "192.168.0.1");

答案 3 :(得分:-2)

你可以简单地写一下:

return  "Current value is " + currentValAsString;