代码之家  ›  专栏  ›  技术社区  ›  Grzenio

C++中的字符串串接

  •  1
  • Grzenio  · 技术社区  · 15 年前

    我是一个经验不足的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());
    }
    

    7 回复  |  直到 15 年前
        1
  •  14
  •   Artyom    15 年前

    我建议:

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

    你的 sprintf snprintf std::stringstream

        2
  •  13
  •   T.E.D.    15 年前

    C++程序员应该做的事情是:

    std::string result = copula.toString() + "(" + left.toString() + "," 
                       + right.toString() + ")";
    
        3
  •  5
  •   Anon.    15 年前

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

        4
  •  4
  •   mingos    15 年前

    因为您似乎在处理std::string,所以根本不需要使用sprintf。string具有易于使用的重载运算符,因此可以使用+=。我认为+也有效,所以只需将std::strings“添加”在一起。

        5
  •  3
  •   Joe    15 年前

        6
  •  3
  •   Emile Cormier    15 年前

    Boost有一个 formatting library 这比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%是字符串。

        7
  •  2
  •   John Dibling    15 年前

    toString() 返回一个 std::string ,

    这:

    copula.toString().c_str(), 左.toString().c_str(), 右.toString().c_str());

    sprintf(结果,” % copula.toString().c_str(),