将文本对齐到字符串C ++的中心 [英] Align text to center in string C++

查看:61
本文介绍了将文本对齐到字符串C ++的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to make a function in C++ for a gameserver DLL which aligns given text to center before returning the new string to Lua for processing. I have spent quite a lot of time looking at examples on various sites but have only been able to find 'cout', which prints it in the console application, which I do not want it to do.

我是C ++的新手,我对如何实现此方法感到非常困惑.如果有人能够提供示例并说明其工作原理,那么我将能够学习如何在将来使用它.

I'm new to C++, and I'm really confused on how to approach this. If someone would be able to provide an example and explain how it works, I'll be able to learn how to do this for the future.

基本上,它是这样做的:

Basically, it does this:

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

以下是我一直在尝试做的事:

Here's a sample of what I've been 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();
}

是哪个版本,但是它将文本输出到控制台,而不是转发回完整的字符串.

Which builds but it prints the text to the console, not forwarding back the completed string.

推荐答案

我假设您已经知道如何从

I'm going to assume you already know how to pass a string from Lua to C++ and return the result from C++ to Lua, so the only part we need to deal with is producing the centered string.

但是,这很简单:

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

这篇关于将文本对齐到字符串C ++的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆