i am writing a program and it works compeletly 100% i take a txt file and read the files from it from infix notation and i transfer them into postfix it works for my first 3 expressions and then after my 3rd expression it goes into a infinite loop? it does not display the rest of my expressions i am sovery confused. i debugged it and i did nto understand why it solves everything before this with no problem at all but then this happens
public static string ChangePostfix(string infix)
{
StringBuilder postfix = new StringBuilder();
char c;
var stack = new Stack<char>();
stack.Push('(');
infix = infix + ")";
int i = 0;
while (stack.Count != 0)
{
if (infix[i] >= '0' && infix[i] <= '9')
{
postfix.Append(infix[i]);
}
else if (infix[i] == '(')
{
stack.Push(infix[i]);
}
else if (infix[i] == '*' || infix[i] == '/' || infix[i] == '%' || infix[i] == '+' || infix[i] == '-')
{
c = stack.Peek();
while (stack.Count != 0 && (c == '*' || c == '/' || c == '%' || c == '+' || c == '-'))
{
if (Precedence(infix[i], c))
postfix.Append(stack.Pop());
c = stack.Peek();
}
stack.Push(infix[i]);
}
else if (infix[i] == ')')
{
for (int j = 0; j < stack.Count && infix[i] != '('; j++)
{
postfix.Append(stack.Pop());
}
stack.Pop();
}
i++;
}
return postfix.ToString();
}
static bool Precedence(char one, char two)
{
if (two == '*' || two == '/' || two == '%')
return true;
if (one == '*' || one == '/' || one == '%')
return false;
return true;
}
static void Main(string[] args)
{
try
{
string[] expressions = File.ReadAllLines(@"expressions.txt");
string infix = string.Empty;
Console.WriteLine("Infix Expression \t\t Postfix Expression \t\t Value");
string postfix = "";
foreach (string str in expressions)
{
infix = str;
Console.Write(str + "\t\t");
//postfix change
postfix = ChangePostfix(infix);
Console.Write(postfix);
Console.WriteLine();
//solve value
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
EXPRESSIONS TXT
1 + 2 - 3 + 4 - 5
1 * 2 * 3 / 2 / 3
1 + 2 * 3 - 4 / 2
1 * 2 + 3 - 4 / 5