用cout语句替换printf

时间:2017-04-20 15:37:56

标签: shell c++11 awk sed

我试图编写一个可以使用cout语句内联替换printf语句的脚本。它可以是sed或awk。

例如,如果printf语句是

printf("int=%d, str=%s", i, s) ;

然后它应该替换为:

cout << "int=" << i << ", str=" << s;

printf语句可能没有。论点。因此,应该生成cout语句并替换为内联。

其他这样的例子可能是:

printf("Statement2: %d %d %s %f", i, j, s ,f);
printf("statement3: %d %f",
        i,
        f);


CString failedMsg;
failedMsg.Format(_T("FAILED Triggered=%d expected=%d in %s"),
                            (int)i,
                            (int)j,
                            static_cast<LPCTSTR>(__TFUNCTION__));

输出:

cout << "Statement2: " << i << " " << j << " " << s << " " << f;
cout << "statement3: " << i << " " << f;

    std::stringstream failedMsg;
    failedMsg << "FAILED Triggered=" << (int)i
        << " expected=" << (int)i
        << " in " << __TFUNCTION__;

是的,我是StackOverflow的新手。我将了解它的工作方式以及如何寻求帮助。但就目前而言,我只是要求您的慷慨支持来解决这个问题。

感谢。

1 个答案:

答案 0 :(得分:0)

───▄██▄─██▄───▄
─▄██████████▄███▄
─▌████████████▌
▐▐█░█▌░▀████▀░░
░▐▄▐▄░░░▐▄▐▄░░░░

  

如果您的printf函数位于一行而不是单独的行,则使用 Perl ;否则我认为你不能

类似于:

printf("int=%d, str=%s", i, s) ;

    std::cout << "one" << '\n'; // just for sure

printf("one=%d, two=%d, three=%d, four=%d, five=%d", a, b   , c, d   ,   e);

    for( int i = 0; i < 10; ++i ){
        std::cout << i << '\n';
    }
你可以:

perl -ne '$T=0;/printf/ && s/printf|[ ",;()]+|%[a-z]/ /g && (@A=split) && ($T=1);if($T){$s=($#A+1)/2;$n=0;print "std::cout << ";print "\"$A[$n] \" << $A[$n+++$s] << " for 1..$s;print q("\n":),"\n";}else{print}' file

输出:

std::cout << "int= " << i << "str= " << s << "\n":

    std::cout << "one" << '\n'; // just for sure

std::cout << "one= " << a << "two= " << b << "three= " << c << "four= " << d << "five= " << e << "\n":

    for( int i = 0; i < 10; ++i ){
        std::cout << i << '\n';
    }

类似于:

printf("Statement2: %d %d %s %f", i, j, s ,f);

std::cout << "one" << '\n'; // just for sure

printf("Statement2: %d %d %s %f", i, j, s ,f);

        for( int i = 0; i < 10; ++i ){
             std::cout << i << '\n';
        }

您可以使用:(作为script.sh)

perl -ne '$T=0;/printf/ && s/printf|[ ",;()]+|%[a-z]/ /g && (@A=split) && ($T=1);if($T){$n=0;print "std::cout << \"$A[0] \" << ";print " $A[++$n] <<" for 1..$#A-1;print q( "\n"),"\n"; }else{print}' file

输出:

std::cout << "Statement2: " <<  i << j << s << "\n"

std::cout << "one" << '\n'; // just for sure

std::cout << "Statement2: " <<  i << j << s << "\n"

        for( int i = 0; i < 10; ++i ){
             std::cout << i << '\n';
        }