AStopher
AStopher

Reputation: 4561

Unexpected characters in console output

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?

Upvotes: 4

Views: 570

Answers (2)

You're using the type string unqualified. I was assuming you have using namespace std somewhere (against best practice), which would make string refer to std::string. But apparently that is not the case, and you have the non-qualified name string defined to something (the question doesn't show what), which behaves similarly to a std::string (i.e. it has .length() and .c_str()). However, the constructor arguments of this something seem to be in reversed order to those of std::string.

If you want your function to work with standard library strings, say so eplicitly:

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

This is a prime example of why it's an extremely good idea to use explicit qualification for std types.

Upvotes: 8

Martze
Martze

Reputation: 921

According to C++ Reference, you are right.

As pointed out in the comments, for the string implementation you use, the arguments are switched.

For the second example, you print the sign (111-1)/2 = 55 = '7' for ' ' = 32 times. Swap the arguments to

string(' ',(111 - s.length()) / 2)

and it should work better.

Upvotes: 2

Related Questions