следующий предложенный код:
- выполняет желаемую операцию
- чисто компилирует
и теперь предложенный код:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//#include <string.h>
#define MAX_SIZE 1000
struct Stack
{
int top;
char arr[MAX_SIZE];
};
struct Stack st;
void init()
{
st.top = -1;
}
bool isEmpty()
{
if(st.top == -1)
{
return true;
}
else
{
return false;
}
}
bool isFull()
{
if(st.top == MAX_SIZE-1)
{
return true;
}
else
{
return false;
}
}
void push(char item)
{
if( isFull() )
{
puts("Stack is full");
}
else
{
st.top++;
st.arr[st.top] = item;
}
}
void pop()
{
if( isEmpty() )
{
puts( "Stack is empty" );
}
else
{
st.top--;
}
}
char gettop()
{
return st.arr[st.top];
}
bool ArePair(char opening,char closing)
{
if( opening == '(' && closing == ')')
return true;
else if( opening == '{' && closing == '}')
return true;
else if( opening == '[' && closing == ']')
return true;
return false;
}
int main( void )
{
init();
char output[MAX_SIZE];
FILE * filepointer;
filepointer = fopen("ajay1.txt", "r");
if(filepointer == NULL)
{
perror("fopen failed");
exit( EXIT_FAILURE );
}
while( fgets(output, sizeof(output), filepointer) )
{
puts( "\n\necho of line read: " );
puts( output );
for( size_t i=0; output[i]; i++ )
{
if( output[i] == '\n' )
{
puts( "finished with current line" );
continue;
}
printf( "Current char under test: %c\n", output[i] );
if(output[i] == '(' || output[i] == '{' || output[i] == '[')
{
push(output[i]);
continue;
}
if(output[i] == ')' || output[i] == '}' || output[i] == ']')
{
if( isEmpty() )
{
puts( "unbalanced pair" );
continue;
}
if( !ArePair( gettop(), output[i]) )
{
puts( "pair not balanced" );
continue;
}
else
{
puts( "pair matched" );
}
pop();
}
}
}
if(isEmpty())
{
puts("\nResult - Valid expression - Perfectly Balanced !");
}
else
{
puts("\nResult - Invalid expression - Not a Balanced one !");
}
fclose(filepointer);
}
Учитывая содержимое опубликованного файла, вот вывод:
echo of line read:
()
Current char under test: (
Current char under test: )
pair matched
finished with current line
echo of line read:
[]
Current char under test: [
Current char under test: ]
pair matched
finished with current line
echo of line read:
[
Current char under test: [
finished with current line
echo of line read:
]
Current char under test: ]
pair matched
finished with current line
echo of line read:
{}
Current char under test: {
Current char under test: }
pair matched
finished with current line
echo of line read:
{
Current char under test: {
finished with current line
Result - Invalid expression - Not a Balanced one !