Reputation: 1922
I'm wanting to display a message on the console window, as long as the message won't exceed the default 0-79 X width of the window.The code I have looks like:
int xRemaining = 80 - mRobot.CurrentPos.X;
string message = "ID{0:d} Facing {1:s} at ({2:d},{3:d}) home is({4:d},{5:d})";
string formatMessage = string.Format(message,mRobot.ID,mRobot.getDir.ToString()/*...*/;
if(mRobot.CurrentPos.Y < 24)
{
if (xRemaining < formatMessage.Length)
{
Console.SetCursorPosition((mRobot.CurrentPos.X - xRemaining), mRobot.CurrentPos.Y+1);
}
else
{
Console.SetCursorPosition(mRobot.CurrentPos.X, mRobot.CurrentPos.Y + 1);
}
}
else
{
if(xRemaining < formatMessage.Length)
{
Console.SetCursorPosition((mRobot.CurrentPos.X-xRemaining), mRobot.CurrentPos.Y-1);
}
else
{
Console.SetCursorPosition(mRobot.CurrentPos.X, mRobot.CurrentPos.Y-1);
}
}
Console.Write(message,,mRobot.ID, mRobot.getDir.ToString(), mRobot.CurrentPos.X, mRobot.CurrentPos.Y,mRobot.Home.X,mRobot.Home.Y);
Edit: Used string.Format, still seems to be running onto the next line though :/
Upvotes: 0
Views: 138
Reputation: 137108
You need to format the string before getting it's length. You are currently getting the length of the unformatted string. To do that you need to use the string.Format
command:
string output = string.Format(message, .....);
....
if (xRemaining < output.Length)
{
....
}
....
Console.Write(output);
Upvotes: 0
Reputation: 27584
You can format message with string.Format
method:
string message = "ID{0:d} Facing {1:s} at ({2:d,3:d}) home is({4:d,5:d})";
string formattedMessage = string.Format(message, mRobot.ID, mRobot.getDir.ToString(), /* ... */);
int msgLength = formattedMessage.Length;
Later on, you can just display it with:
Console.WriteLine(formattedMessage);
Upvotes: 1