When I debug this console application, it's giving a strange result. There's obviously something I'm overlooking.
class Program
{
static void Main(string[] args)
{
int ops = int.Parse(Console.ReadLine());
int inte = 0;
StringBuilder roll = new StringBuilder();
Operations(roll, inte, ops);
}
static void Operations(StringBuilder roll, int inte, int ops)
{
for (int i = 0; i < ops; i++)
{
roll.AppendLine(Console.ReadLine());
inte = roll.ToString().IndexOf("^");
if (inte == i)
roll.Remove(i, 1);
if (roll.ToString().IndexOf("!") == i)
roll.Remove(i, 1);
}
Console.WriteLine(roll.ToString());
Console.ReadLine();
}
}
For inputs, type in "3" for the first input (integer "inte"), and "^A", "^B" "^D" for the other 3 ReadLine entries. On the first iteration of the loop, it will remove the ^ as expected. But on the second iteration (i =1), it reads inte as 3. But it should be 1, because on the second round the Stringbuilder has appended "^B" to A, so it's now "A^B". I'm trying to remove the "^"s (and "!"s too) when they're entered as the stringbuilder is appending the strings. Why is the "inte" integer reading 3 on the second round?
This is your problem:
roll.AppendLine(Console.ReadLine());
You're using AppendLine
, so on the first iteration it's appending "^A" and then a carriage return ('\r'
) and line feed ('\n'
). After removing the first character, you've still got 3 characters in the string. ('A'
, '\r'
and '\n'
). That's why after appending ^B\r\n" in the second iteration, you find the
^` at index 3 rather than index 1.
Just change it to:
roll.Append(Console.ReadLine());
and I suspect you'll get the results you're expecting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With