4

I am programming a new server-client network for the game Crysis Wars. I have a function that centers a string to the amount of characters supported per-line in the console window. The window fits 113 characters, but I have set the maximum character width in my function to 111 as to fit text nicely.

This is my function:

string Main::CenterText(string s)
{
    return string((111 - s.length()) / 2, ' ') + s; 
}

This function is from a question I asked last year, but I however am not sure whether I ended up using it or not in past projects.

I am attempting to use this function in this context (the CryLogAlways function simply logs the string to the game/server logfile and prints it):

CryLogAlways(CenterText("   ____     ____      _ __      _  _  __").c_str());
CryLogAlways(CenterText("  /  _/__  / _(_)__  (_) /___ _( )| |/_/").c_str());
CryLogAlways(CenterText(" _/ // _ \\/ _/ / _ \\/ / __/ // //_>  <  ").c_str());
CryLogAlways(CenterText("/___/_//_/_//_/_//_/_/\\__/\\_, / /_/|_|  ").c_str());
CryLogAlways(CenterText("                         /___/          ").c_str());

However the output is:

enter image description here

Likewise as @deW1 requested, I have a similar output with CryLogAlways(CenterText("X").c_str());:

enter image description here

Why am I getting this output, and how can I fix this?

4

2 に答える 2

8

string非修飾型を使用しています。私はあなたが(ベストプラクティスに反して)using namespace stdどこかにあると仮定していました。しかし、明らかにそうではなく、何かに非修飾名が定義されています(質問は何を示していません)。ただし、このsomethingのコンストラクター引数は、 のコンストラクター引数の順序が逆になっているようです。stringstd::stringstringstd::string.length().c_str()std::string

関数を標準ライブラリの文字列で動作させたい場合は、明示的に次のように言います。

std::string Main::CenterText(std::string s)
{
    return std::string((111 - s.length()) / 2, ' ') + s; 
}

これは、型に明示的な修飾を使用することが非常に優れている理由の代表的な例ですstd

于 2014-11-21T14:38:44.460 に答える