2012-06-11 115 views
1

我想创建一个公共的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 

我只是想知道什么可能是一个更好的方式来完成这项任务。

+0

在这里看到:http://stackoverflow.com/a/10410159/1025391 – moooeeeep

+0

其他可能重复:http://stackoverflow.com/q/2342162/1025391 – moooeeeep

回答

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"; 
} 

或者,如果您不能或不想使用升压:

#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! 
+0

看起来不错的选择。 :) –

+0

这是如何工作的? valist? – Dennis

+0

[总而言之,格式类将格式字符串(最终具有类似printf的指令)转换为内部流上的操作,最后将格式化结果作为字符串或直接返回到输出流中。] (http://www.boost.org/doc/libs/1_49_0/libs/format/doc/format.html#how_it_works) – moooeeeep

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

    return buff; 
} 
-2

你可以简单地写这个:

return "Current value is " + currentValAsString; 
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"); 
+0

你应该使用'= {0}'初始化你的缓冲区,并且有一个vsnprintf模板用于确保缓冲区不被溢出。 – Dennis

+0

你是对的,实际上,1024大小的缓冲区可能是一个潜在的bug :) – Aladdin