2016-07-13 3 views
1

私はsystem()呼び出しに渡す文字列を書式設定するのにboost::format(私はC++ 98を使用しているので、std::ではありません)を使用しています。なぜstd/boost :: formatはこのc_str()の動作を引き起こしますか?

formatで作成された文字列のc_str()を取得すると、文字列の途中で終了するようです。リテラル値で作成された同じスティングには同じ問題はありません。何が起きてる?

ブースト使用1.46.1BOOST_VERSIONに従って。私system()コールにc_str()を渡す

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

int main(int argc, char** argv) 
{ 
    const std::string my_str = "echo '/%1%/ some other stuff'"; 
    boost::format fmtr(my_str); 
    fmtr % "sleep 3"; // should read: echo '/sleep 3/ some other stuff' 

    std::cout << "1: " << fmtr.str() << "\n";   // 1. echo '/sleep 3/ some other stuff' (OK) 
    std::cout << "2: " << fmtr.str().c_str() << "\n"; // 2. echo '/sleep 3      (BAD) 

    // Try the c_str of a string not created through boost::format 
    const std::string finished = "echo '/sleep 3/ some other stuff'"; 
    std::cout << "3: " << finished.c_str() << "\n"; // 3. echo '/sleep 3/ some other stuff' (OK) 

    // Try copying the string from format to see if that makes any difference (it doesn't) 
    std::string copy = fmtr.str(); 
    std::cout << "4: " << copy.c_str() << "\n";  // 4. echo '/sleep 3      (BAD) 
    return 0; 
} 

は誤差が生じている。おそらく

sh -c: line 0: unexpected EOF while looking for matching `'' 

それは同様途中の文字列に沿って仕上げているので。適切で

+1

あなたの行動を再現することはできません、それは特定のブーストまたはSTDC++バージョンのためのバグであるように見える、私は – Slava

+0

あなたが ''と ''ない 'を'含むべきと 'main'が – Slava

+0

int''返さなければなりませんその情報を提供申し訳ありません、あなたの使用法は正しいと思われます、私の悪い。 –

答えて

0

は、プログラムが正常に動作していますideone

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

int main() 
{ 
    const std::string my_str = "echo '/%1%/ some other stuff'"; 
    boost::format fmtr(my_str); 
    fmtr % "sleep 3"; // should read: echo '/sleep 3/ some other stuff' 

    std::cout << "1: " << fmtr.str() << "\n";   // 1. echo '/sleep 3/ some other stuff' (OK) 
    std::cout << "2: " << fmtr.str().c_str() << "\n"; // 2. echo '/sleep 3      (BAD) 

    // Try the c_str of a string not created through boost::format 
    const std::string finished = "echo '/sleep 3/ some other stuff'"; 
    std::cout << "3: " << finished.c_str() << "\n"; // 3. echo '/sleep 3/ some other stuff' (OK) 

    // Try copying the string from format to see if that makes any difference (it doesn't) 
    std::string copy = fmtr.str(); 
    std::cout << "4: " << copy.c_str() << "\n";  // 4. echo '/sleep 3      (BAD) 
} 

あなたは、修正し、メインの種類を返し、もう一度試してみてください。間違った動作が続く場合は、おそらくあなたはC++のバージョンを壊している、そして/または、ライブラリを増強しています。

関連する問題