繁体   English   中英

在C ++中串联字符串

[英]Concatenating strings in C++

我不是经验丰富的C ++程序员,所以这个问题可能很基本。 我正在尝试获取copula的文件名:

string MonteCarloBasketDistribution::fileName(char c)
{
    char result[100];
    sprintf(result, "%c_%s(%s, %s).csv", copula.toString().c_str(), left.toString().c_str(), right.toString().c_str());
    return string(result);
}

用于:

MonteCarloBasketDistribution::MonteCarloBasketDistribution(Copula &c, Distribution &l, Distribution &r): copula(c), left(l), right(r)
{
    //.....
    ofstream funit;
    funit.open (fileName('u').c_str());

    ofstream freal;
    freal.open (fileName('r').c_str());
}

但是,创建的文件具有垃圾名称,主要由奇怪的字符组成。 知道我在做什么错以及如何解决吗?

sprintf有4个占位符,而您仅给出3个参数。

我会建议:

string MonteCarloBasketDistribution::fileName(char c) {
   std::ostringstream result;
   result << c <<"_"<<copula<<'('<<left<<", "<<right<<").csv";
   return result.str();
}

您的sprintf对于缓冲区溢出并不安全,请使用C99 snprintfstd::stringstream

由于您要共同处理的所有事情都是基于字符的,因此使用sprintf有点愚蠢。

C ++程序员应该做什么呢?

std::string result = copula.toString() + "(" + left.toString() + "," 
                   + right.toString() + ")";

您的格式字符串中有四个说明符,但仅提供了三个附加参数。

由于您似乎在std :: string上工作,因此根本不需要使用sprintf。 std :: string具有易于使用的重载运算符,因此您可以使用+ =来合并字符串。 我认为+也可以,所以只需将“ std :: strings”添加在一起。

看起来完全坏掉的唯一一件事是,您只向sprintf传递了3个数据参数,但期望值为4(%c,%s,%s,%s)

Boost具有一个格式化库 ,比printf和朋友更安全。

#include <boost/format.hpp>
string MonteCarloBasketDistribution::fileName(char c)
{
    return boost::str( boost::format("%c_%s(%s, %s).csv")
        % c % copula.toString() % left.toString() % right.toString() );
}

或者,或者:

#include <boost/format.hpp>
string MonteCarloBasketDistribution::fileName(char c)
{
    return boost::str( boost::format("%1%_%2%(%3%, %4%).csv")
        % c % copula.toString() % left.toString() % right.toString() );
}

在后一个示例中,Boost通过“查看”通过%运算符传递的参数类型,知道%1%是字符,%2%至%4%是字符串。

假设toString()返回一个std::string

这个:

sprintf(结果,“%c_%s(%s,%s).csv”,copula.toString()。c_str(),left.toString()。c_str(),right.toString()。c_str()) ;

...应该:

sprintf(结果,“ %s _%s(%s,%s).csv”,copula.toString()。c_str(),left.toString()。c_str(),right.toString()。c_str() );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM