0

我一直在尝试在 C++ 中为游戏服务器 DLL 创建一个函数,该函数在将新字符串返回到 Lua 进行处理之前将给定的文本对齐到中心。我花了很多时间查看各个站点上的示例,但只能找到“cout”,它会在控制台应用程序中打印它,我不希望它这样做。

我是 C++ 新手,我真的很困惑如何处理这个问题。如果有人能够提供一个例子并解释它是如何工作的,我将能够学习如何在未来做到这一点。

基本上,它这样做:

  1. 将我们的字符串从 Lua 转发到 C++。
  2. C++ 将我们刚刚转发的字符串居中。
  3. 将完成的字符串返回给 Lua。

这是我一直在尝试做的一个示例:

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();
}

哪个构建但它将文本打印到控制台,而不是转发回完整的字符串。

4

3 回答 3

3

我假设你已经知道如何将字符串从Lua传递到 C++ 并将结果从 C++ 返回到 Lua,所以我们需要处理的唯一部分就是生成居中的字符串。

然而,这很容易:

std::string center(std::string input, int width = 113) { 
    return std::string((width - input.length()) / 2, ' ') + input;
}
于 2013-07-07T15:26:43.293 回答
1

这是另一种确保文本在给定宽度内居中并用空格左右填充的方法。

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();
}

这可以写得更优雅或更简洁。

于 2013-09-03T19:34:26.027 回答
0
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;
}
于 2019-08-21T14:57:44.293 回答