Center text in C ++ line

I am trying to create a C ++ function for the gameserver dll that aligns the given text to the center before returning a new line to Lua for processing. I spent a lot of time on examples on different sites, but I was able to find a "cout" that prints it in a console application, and I do not want him to do this.

I'm new to C ++ and I'm really confused about how to approach this. If someone can provide an example and explain how it works, I can learn to do it in the future.

Basically, he does this:

  • Send our line from Lua to C ++.
  • C ++ focuses the line we just redirected.
  • Bring the completed line back to Lua.

Here is an example of what I was trying to do:

int CScriptBind_GameRules::CentreTextForConsole(IFunctionHandler *pH, const char *input)
{
    if (input)
    {
        int l=strlen(input);
        int pos=(int)((113-l)/2);
        for(int i=0;i<pos;i++)
            std::cout<<" ";
        std::cout<<input;
        return pH->EndFunction(input); 
    }
    else
    {
        CryLog("[System] Error in CScriptBind_GameRules::CentreTextForConsole: Failed to align");
        return pH->EndFunction();
    }
    return pH->EndFunction();
}

, , .

-1
3

, , Lua ++ ++ Lua, , , .

, , :

std::string center(std::string input, int width = 113) { 
    return std::string((width - input.length()) / 2, ' ') + input;
}
+2

, .

std::string center(const std::string s, const int w) {
    std::stringstream ss, spaces;
    int pad = w - s.size();                  // count excess room to pad
    for(int i=0; i<pad/2; ++i)
        spaces << " ";
    ss << spaces.str() << s << spaces.str(); // format with padding
    if(pad>0 && pad%2!=0)                    // if pad odd #, add 1 more space
        ss << " ";
    return ss.str();
}

elgantly .

+1
std::string center (const std::string& s, unsigned width)
{
    assert (width > 0);
    if (int padding = width - s.size (), pad = padding >> 1; pad > 0)
        return std::string (padding, ' ').insert (pad, s);
    return s;
}
0

All Articles