C program which counts lines and operators wrong - c

This program should read rows and count operators, but counts wrong and can not find out where the errors are.
Help me find out the bugs and fix the program to be able to count rows and operators correctly.I've already tried several ways to fix it and it still counts wrong.
Current output:Broqt na operatorite e:1
Broqt na redovete e:1119
Expected output: Broqt na operatorite e:11
Broqt na redovete e:221
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
void cycleOperatorsCounter(FILE* inputStream, FILE* outputStream);
void counter(FILE* inputStream, FILE* outputStream);
int fileToFile(void);
int fileToScreen(void);
int screenToFile(void);
int screenToScreen(void);
void getFileName(char* fileName, int mode);
int menu() {
int i;
printf("----1. FILE TO FILE \n");
printf("----2. FILE TO SCREEN \n");
printf("----3. KBRD TO FILE \n");
printf("----4. KBRD TO SCREEN \n");
printf("----0. EXIT \n");
do {
printf("SELECT OPTION: ");
fflush(stdin);
scanf("%i", &i);
} while (i < 0 || i> 4);
return i;
}
int main(void) {
while (1) {
system("cls");
switch (menu()) {
case 1: fileToFile();
break;
case 2: fileToScreen();
break;
case 3: screenToFile();
break;
case 4: screenToScreen();
break;
default:
return 0;
}
system("pause");
}
}
void getFileName(char* fileName, int mode) {
while (1) {
fflush(stdin);
if (mode == 1) {
printf("Input file name(.C): ");
gets(fileName);
if (fileName[strlen(fileName) - 2] == '.' && toupper(fileName[strlen(fileName) - 1]) == 'C') {
return;
}
}
else {
printf("Output File: ");
gets(fileName);
return;
}
}
}
int fileToFile(void) {
char inputFileName[256], outputFileName[256];
FILE *inputStream, *outputStream;
getFileName(inputFileName, 1);
if (!(inputStream = fopen(inputFileName, "r"))) {
fprintf(stderr, "Error opening file!\n");
return -1;
}
getFileName(outputFileName, 2);
if (!(outputStream = fopen(outputFileName, "w"))) {
fprintf(stderr, "Error opening file!\a\n");
return -1;
}
cycleOperatorsCounter(inputStream, outputStream);
rewind(inputStream);
counter(inputStream, outputStream);
fclose(inputStream);
fclose(outputStream);
printf("Results saved to \"%s\".\n", outputFileName);
return 0;
}
int fileToScreen(void) {
char inputFileName[256];
FILE* inputStream;
getFileName(inputFileName, 1);
if (!(inputStream = fopen(inputFileName, "r"))) {
fprintf(stderr, "Error opening file!\n");
return -1;
}
cycleOperatorsCounter(inputStream, stdout);
rewind(inputStream);
counter(inputStream, stdout);
fclose(inputStream);
return 0;
}
int screenToFile(void) {
char outputFileName[256];
FILE *outputStream, *tempStream;
char str[999];
tempStream = fopen("temp.tmp", "w");
fflush(stdin);
printf("Napishete \"KRAI\" na nov red, kogato vuvedete teksta\n");
while (1) {
gets(str);
if (!strcmp(str, "KRAI")) {
fclose(tempStream);
tempStream = fopen("temp.tmp", "r");
break;
}
fprintf(tempStream, "%s\n", str);
}
getFileName(outputFileName, 2);
if (!(outputStream = fopen(outputFileName, "w"))) {
fprintf(stderr, "Error opening file!\a\n");
return -1;
}
cycleOperatorsCounter(tempStream, outputStream);
rewind(tempStream);
counter(tempStream, outputStream);
fclose(tempStream);
fclose(outputStream);
printf("Results saved to \"%s\".\n", outputFileName);
return 0;
}
int screenToScreen(void) {
FILE *tempStream;
char str[999];
tempStream = fopen("temp.tmp", "w");
fflush(stdin);
printf("Napishete \"KRAI\" na nov red, kogato vuvedete teksta\n");
while (1) {
gets(str);
if (!strcmp(str, "KRAI")) {
fclose(tempStream);
tempStream = fopen("temp.tmp", "r");
break;
}
fprintf(tempStream, "%s\n", str);
}
cycleOperatorsCounter(tempStream, stdout);
rewind(tempStream);
counter(tempStream, stdout);
fclose(tempStream);
return 0;
}
void cycleOperatorsCounter(FILE* inputStream, FILE* outputStream) {
char str[1000];
int cycleCounter = 0;
unsigned i;
while (fgets(str, sizeof(str), inputStream) != NULL) {
for (i = 0; i < strlen(str); i++) {
if ((str[i-1] == ' ' || str[i-1] == '\n' || str[i-1] == '\t' || i==0) &&
(str[i] == 'i') && (str[i + 1] == 'f') && (str[i+3] == ' ' || str[i+3] ==
'\n' || str[i+3] == '\t')) {
cycleCounter++;
}
if ((str[i-1] == ' ' || str[i-1] == '\n' || str[i-1] == '\t' ||
i==0)
&& (str[i] == 'e') && (str[i + 1] == 'l') && (str[i + 2] == 's')
&& (str[i + 3] == 'e')
&& (str[i+5] == ' ' || str[i+6] == '\n' || str[i+7] ==
'\t')) {
cycleCounter++;
}
}
}
fprintf(outputStream, "Broqt na operatorite za cikul e: %d\n",
cycleCounter);
}
void counter(FILE* inputStream, FILE* outputStream) {
char str[1000];
int Counter = 0;
unsigned i;
while (fgets(str, sizeof(str), inputStream) != NULL) {
for (i = 0; i < strlen(str); i++) {
{
if ((str[i-1] == ' ' || str[i-1] == '\n' || str[i-1] == '\t' || i==0))
{
Counter++;
}
}
}
}
fprintf(outputStream, "Broqt na redovete e: %d\n", Counter);
}

This is prefaced by my top comments.
That is, finding the if and the else is more easily done with strtok and strcmp.
And, to count rows/lines, simply doing fgets and counting or doing fgetc and counting the \n will work.
Hopefully, this will get you farther:
void
cycleOperatorsCounter(FILE *inputStream, FILE *outputStream)
{
char *bp;
char *tok;
char str[1000];
int cycleCounter = 0;
while (fgets(str, sizeof(str), inputStream) != NULL) {
bp = str;
while (1) {
tok = strtok(bp," \t\n");
if (tok == NULL)
break;
bp = NULL;
if (strcmp(tok,"if") == 0) {
cycleCounter++;
continue;
}
if (strcmp(tok,"else") == 0) {
cycleCounter++;
continue;
}
}
}
fprintf(outputStream, "Broqt na operatorite za cikul e: %d\n",
cycleCounter);
}
void
counter(FILE *inputStream, FILE *outputStream)
{
int Counter = 0;
// count number of lines
// NOTE: either of these should work:
#if 1
char str[1000];
while (fgets(str, sizeof(str), inputStream) != NULL)
++Counter;
#else
while (1) {
int chr = fgetc(inputStream);
if (chr == EOF)
break;
if (chr == '\n')
++Counter;
}
#endif
fprintf(outputStream, "Broqt na redovete e: %d\n", Counter);
}

Related

How to skip NULL file

My code traverses through command line arguments. if the command line contains "alice.txt" index zero of an empty array is filled with "alice.txt" This also applies to "anh.txt" if it is present, then index 1 is filled with "anh.txt". When i type in the command line ./wc alice.txt anh.txt it will print out words line and characters of both files. however if I just do /wc anh.txt i will get "NULL FILE" I suspect this is because of index zero being NULL, I wrote it so it would print "NULL FILE" and then exit the program. How can I modify my code so it doesn't exit, rather skips to the next index? This is what I have for code:
int main(int argc, char **argv)
{
int argArray[argc];
char *nameArray[argc];
for (int i = 1; i < argc; i ++)
{
if (strcmp(argv[i], "-l") == 0)
{
argArray[0] = 1;
}
if (strcmp(argv[i], "-w") == 0)
{
argArray[1] = 1;
}
if (strcmp(argv[i], "-c") == 0)
{
argArray[2] = 1;
}
if (strcmp(argv[i], "alice.txt") == 0)
{
nameArray[0] = "alice.txt";
}
if (strcmp(argv[i], "anh.txt") == 0)
{
nameArray[1] = "anh.txt";
}
if ((strcmp(argv[i], "-l") != 0) && (strcmp(argv[i], "-c") != 0 ) && (strcmp(argv[i], "-w") != 0 ) && (strcmp(argv[i], "-w") != 0) && (strcmp(argv[i], "alice.txt") != 0) && (strcmp(argv[i], "anh.txt") != 0))
{
printf("%s is an invalid argument or file\n", argv[i]);
}
}
if ((argArray[0] != 1) && (argArray[1] != 1) && (argArray[2] != 1))
{
argArray[0] = 1;
argArray[1] = 1;
argArray[2] = 1;
}
int *myArrayAlice = get_counts2(nameArray[0]);
print_counts(argArray, myArrayAlice, *nameArray);
printf(" alice.txt\n");
int *myArrayAnh = get_counts(nameArray[1]);
print_counts(argArray,myArrayAnh, *nameArray);
printf(" anh.txt\n");
int *myArrayTotal2 = get_counts2(nameArray[1]);
print_counts(argArray, myArrayTotal2, *nameArray);
printf(" total\n");
return 0;
}
int *get_counts(char *filename)
{
FILE *file = fopen(filename, "r");
if (file == NULL)
{
printf("NULL FILE");
//exit(1);
}
int c;
bool whitespace = true;
int *arr = calloc(3,sizeof(int));
for(;;)
{
c = fgetc(file);
if (c == EOF)
{
break;
}
else if (c == '\n')
{
arr[0]++;
}
else if (whitespace && !isspace(c))
{
arr[1]++;
whitespace = false;
}
else if (!whitespace && isspace(c))
{
whitespace = true;
}
arr[2]++;
}
fclose(file);
return arr;
}
int *get_counts2(char *filename)
{
FILE *file = fopen(filename, "r");
if (file == NULL)
{
printf("NULL FILE");
//exit(1);
}
int c;
bool whitespace = true;
static int arr[3] = {0,0,0};
for(;;)
{
c = fgetc(file);
if (c == EOF)
{
break;
}
else if (c == '\n')
{
arr[0]++;
}
else if (whitespace && !isspace(c))
{
arr[1]++;
whitespace = false;
}
else if (!whitespace && isspace(c))
{
whitespace = true;
}
arr[2]++;
}
fclose(file);
return arr;
}

exec failed with fork() and execvp()

I am currently working on a program in which I have to write a shell in C. I am having trouble getting the fork() section of my program to work. Here is my code:
void execute_func(char** tok)
{
pid_t pid = fork();
if (pid == -1)
{
printf("\nERROR: forking child process failed\n");
return;
}
else if (pid == 0)
{
if (execvp(tok[0], tok) < 0)
{
printf("ERROR: exec failed\n");
}
exit(0);
}
else
{
wait(NULL);
return;
}
}
for example, if I am to type in any sort of function such as "ls" or "wc" it gives me the "ERROR: exec failed" message, which means that the fork() is not running correctly. This could be a small issue in my understanding of fork() but I am completely stumped.
here is my whole program:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
char str[129];
enum {NOT_FOUND=0,FOUND};
enum {false=0,true};
static char *ptr;
const char *del;
int ReadLine(char *, int , FILE *);
char *mystrtok(char* string,const char *delim)
{
int j,flag=NOT_FOUND;
char *p;
if(string != NULL)
{
ptr=string;
p=string;
}
else
{
if(*ptr == '\0')
return NULL;
p=ptr;
}
while(*ptr != '\0')
{
del=delim;
while(*del != '\0')
{
if(*ptr == *del)
{
if(ptr == p)
{
p++;
ptr++;
}
else
{
*ptr='\0';
ptr++;
return p;
}
}
else
{
del++;
}
}
ptr++;
}
return p;
}
void execute_func(char** tok)
{
pid_t pid = fork();
if (pid == -1)
{
printf("\nERROR: forking child process failed\n");
return;
}
else if (pid == 0)
{
if (execvp(tok[0], tok) < 0)
{
printf("ERROR: exec failed\n");
}
exit(0);
}
else
{
wait(NULL);
return;
}
}
int main()
{
int i;
char *p_str,*token;
char delim[10];
delim[0] = ' ';
delim[1] = '\t';
delim[2] = '\n';
delim[3] = '\0';
char cwd[1024];
char *tok[129];
while(1)
{
tok[0] = NULL;
fflush(stdin);
fflush(stdout);
printf("\n Enter a string to tokenize: ");
// printf("\n before scan");
fflush(stdin);
// printf("\n fflush");
ReadLine(str, 128, stdin);
/* scanf("%[^\n]",str); */
printf("\n after scan");
for (i = 1, p_str = str; ; i++, p_str = NULL)
{
token = mystrtok(p_str,delim);
if (token == NULL)
break;
printf("%d: %s\n",i,token);
tok[i-1] = token;
printf("%s\n",tok[i-1]);
}
if(tok[0] != NULL)
{
if(strcmp(tok[0],"cd") == 0)
{
if (chdir(tok[1]) != 0)
perror("chdir() error()");
getcwd(cwd, sizeof(cwd));
printf("current working directory is: %s\n", cwd);
}
else if(strcmp(tok[0],"pwd") == 0)
if (getcwd(cwd, sizeof(cwd)) == NULL)
perror("getcwd() error");
else
printf("current working directory is: %s\n", cwd);
else if(strcmp(tok[0],"exit") == 0)
exit(3);
else
{
execute_func(tok);
}
}
}
}
int ReadLine(char *buff, int size, FILE *fp)
{
buff[0] = '\0';
buff[size - 1] = '\0'; /* mark end of buffer */
char *tmp;
if (fgets(buff, size, fp) == NULL)
{
*buff = '\0'; /* EOF */
return false;
}
else
{
/* remove newline */
if ((tmp = strrchr(buff, '\n')) != NULL)
{
*tmp = '\0';
}
}
return true;
}
Problem appears to be here:
if (token == NULL)
break;
printf("%d: %s\n",i,token);
tok[i-1] = token;
The trailing NULL never gets set in tok thus resulting in execve not finding the end of the list. Like this should fix it:
tok[i-1] = token;
if (token == NULL)
break;
printf("%d: %s\n",i,token);

why this program ends when i type the first word and doesn't loop back

i want to make the programm loop again and again until i type the endword ****TELOS
/* 1 */ int text_input();
int main() {
int number;
text_input();
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
printf("Enter the text. (****TELOS for stoping)");
char endword[10];
strcpy(endword, "****TELOS");
char temp[N];
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}
I think your code doesn't work because you don't have set each item of endword to 0
so your code should be like that
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 10
#define M 10
int text_input(char words[M][N]);
int main() {
char a[M][N];
text_input(a);
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
char temp[N];
char endword[10] = {0,0,0,0,0,0,0,0,0,0};
printf("Enter the text. (****TELOS for stoping)");
strcpy(endword, "****TELOS");
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}

Cannot understand why program crashes after a couple iterations of while loop?

I am writing the following program to parse the text file (attached) but it keeps crashing after couple of iterations of while loop or it seems that the buffer storing file contents is corrupted somehow?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char * pick_question(char *, char, int);
char * print_answer(char *, char, int);
int no_of_questions(char*, char);
void clear();
int debug = 0;
int main(int argc, char* argv[])
{
system("cmd /c chcp 1252");
// system("cmd /c chcp 65001");
if (argc < 2)
{
perror("Please enter a filename!\n");
exit(0);
}
if (argc > 2)
{
debug = atoi(argv[2]);
}
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
if (!file)
{
perror("Unable to read file!\n");
exit(0);
}
else
{
if (debug == 1)
{
printf("File opened successfully\n");
}
}
static char *buffer;
int fileSz;
fseek(file, 0, SEEK_END);
fileSz = ftell(file);
fseek(file, 0, SEEK_SET);
buffer = (char*) malloc((fileSz + 1) * sizeof(char));
if (!buffer)
{
perror("Unable to allocate buffer!");
exit(0);
}
fread(buffer, sizeof(char), fileSz, file);
while (1)
{
time_t t;
srand((unsigned) time(&t));
int sub = rand() % 5 + 1;
char del;
switch (sub)
{
case 1:
del = 'A';
break;
case 2:
del = 'B';
break;
case 3:
del = 'C';
break;
case 4:
del = 'D';
break;
case 5:
del = 'E';
}
int nrOfQues = no_of_questions(buffer, del);
if (nrOfQues == 0)
{
perror("main(): no_of_questions() returned 0. Unsupported text structure in file or incorrect file encoding!");
fclose(file);
exit(0);
}
int qNo = rand() % nrOfQues + 1;
char *ques = pick_question(buffer, del, qNo);
if (ques)
{
printf("\n\n");
puts(ques);
printf("\n\n");
}
else
{
perror("main(): pick_question() returned NULL. Unsupported text structure in file!");
fclose(file);
exit(0);
}
printf("\n\n");
printf("Do you want to see the answer(y/n)?");
char ans, repeat;
scanf("%c", &ans);
if ( ans == 'Y' || ans == 'y')
{
char *ans = print_answer(buffer, del, qNo);
if (ans)
{
printf("\n\n");
puts(ans);
printf("\n\n");
}
else
{
printf("\n\n");
perror("main(): print_answer() returned NULL. Unsupported text structure in file!");
fclose(file);
exit(0);
}
}
printf("Do you want to try more questions (y/n)?");
clear();
scanf("%c", &repeat);
if (repeat == 'N' || repeat == 'n')
{
break;
}
clear();
}
printf("\n\n");
printf("******** Thank you for using TULE Master! ********");
printf("\n\n");
fclose(file);
return 0;
}
char * pick_question(char * buffer, char sub, int qNo)
{
char tmpBuff[20];
char tmpBuff2[20];
const char * searchStr = "FRÅGA";
const char * searchStr2 = "A 1 SVAR:";
const char * searchStr3 = "*****************************************";
char *pStr, *currPos, *nStr, *tmpStr, *tmpStr2;
currPos = buffer;
int count = snprintf(tmpBuff, 20, "FRÅGA %c %d", sub, qNo);
if (count >= 0 || count < 20)
{
if (debug)
{
printf("tmpBuff is %s\n", tmpBuff);
}
currPos = strstr(currPos, tmpBuff);
if (currPos)
{
pStr = currPos;
nStr = currPos + 1;
nStr = strstr(nStr, searchStr);
if (!nStr)
{
nStr = currPos;
nStr = strstr(nStr, searchStr2);
if (!nStr)
{
printf("pick_qestion(): nStr is NULL. Unsupported "
"text structure");
return NULL;
}
}
// Check if it is a scenario based question
count = snprintf(tmpBuff2, 20, "FRÅGA %c %d", sub, qNo-1);
if (count >= 0 || count < 20)
{
tmpStr = strstr(buffer, tmpBuff2);
tmpStr2 = strstr(tmpStr, searchStr3);
if (tmpStr < tmpStr2 && tmpStr2 < pStr)
{
pStr = tmpStr2;
}
}
int qLen = nStr - pStr;
char *ques = malloc(sizeof(char) * (qLen+1));
snprintf(ques,qLen,"%s", pStr);
return ques;
}
else
{
printf("pick_qestion(): string \"FRÅGA\" not found in file!");
return NULL;
}
}
printf("pick_qestion(): snprintf was not successful!");
return NULL;
}
char * print_answer(char * buffer, char sub, int qNo)
{
char tmpBuff[20];
char *pStr, *currPos, *nStr;
int count = snprintf(tmpBuff, 20, "%c %d SVAR:", sub, qNo);
if (count >= 0 || count < 20)
{
currPos = strstr(buffer, tmpBuff);
if (!currPos)
{
printf("print_answer(): string \"SVAR\" not found in file!");
}
pStr = currPos;
nStr = currPos + 1;
char tmpBuff2[20];
int count = snprintf(tmpBuff2, 20, "%c %d SVAR:", sub, qNo+1);
if (count < 0 || count >= 20)
{
printf("print_answer(): snprint was not successful!");
return NULL;
}
nStr = strstr(nStr, tmpBuff2);
if (!nStr)
{
nStr = buffer + strlen(buffer);
}
int ansLen = nStr - pStr;
char *ans = malloc(sizeof(char) * (ansLen+1));
snprintf(ans, ansLen, "%s", pStr);
return ans;
}
printf("print_answer(): snprint was not successful!");
return NULL;
}
int no_of_questions(char *buffer, char sub)
{
char tmpBuff[20];
char *currPos, *pStr;
int count = snprintf(tmpBuff, 20, "FRÅGA %c", sub);
if (count >= 0 || count < 20)
{
if (debug)
{
printf("tmpBuff is %s\n", tmpBuff);
}
currPos = strstr(buffer, tmpBuff);
while (currPos != NULL)
{
pStr = currPos;
currPos = currPos + 1;
currPos = strstr(currPos, tmpBuff);
}
if (pStr != buffer)
{
pStr += 9;
char tmpBuff2[20];
memcpy(tmpBuff2, pStr, 2);
if (debug)
{
printf("No. of questions for %c DEL is are %d\n", sub,
atoi(tmpBuff2));
}
return atoi(tmpBuff2);
}
return 0;
}
return 0;
}
void clear()
{
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
}
This is the file that is given as input to the program:
Link

Line in text file is evaluated multiple times?

I need to convert infix to postfix and evaluate postfix expression. When reading from a file, I should be able to evaluate multiple expressions at once. But when I run it and it encounters an expression that is not well-formed in the sense that there are more closed parentheses than open ones, it evaluates that expression 2 or 3 times.
Code:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX 1000
typedef struct stack
{
int data[MAX];
int top;
} stack;
int priority(char);
void init(stack*);
int empty(stack*);
int full(stack*);
char pop(stack*);
void push(stack*, char);
char top(stack*);
void add(char*, char, int);
void keyboard();
void read_file();
int change(char);
void pushYO(double);
double popYO();
stack s;
char x;
int i, token, topYO = -1;
double result[MAX];
char filepath[MAX];
int main()
{
char choice;
init(&s);
system("CLS");
printf("[1] Keyboard \n[2] Read from text file \n[3] Exit \n");
scanf("%c", &choice);
if(choice != '1' && choice != '2' && choice != '3')
{
main();
}
else if(choice == '1')
{
keyboard();
}
else if(choice == '2')
{
read_file();
}
else if(choice == '3')
{
printf("\nThank you for using Kei Shirabe's \ninfix to postfix converter and evaluator! :)\n");
exit(0);
}
}
void keyboard() //the keyboard input version. this works fine
{
//code here
}
void read_file()
{
int z, count, form, paren;
double one, two, three = 1;
char infx[MAX];
char pofx[MAX];
char choice;
FILE *text = fopen("text.txt", "a");
printf("Enter path of file:");
scanf("%s",&filepath);
FILE *textYO = fopen(filepath, "r");
if((textYO) == NULL)
{
printf("\nError! Unable to open %s\n\n", filepath);
}
else
{
while((fgets(infx, MAX, textYO))!= NULL)
{
form = -1, paren = 0, count = 0, z = 0;
infx[
strlen(infx)-1] = '\0';
for (i=0; i<strlen(infx); i++)
{
if((token = infx[i]) != '\n')
{
if(isalnum(token))
{
form++;
}
else
{
if(token == '(')
{
paren++;
}
else if(token == ')')
{
paren--;
}
else
{
form--;
}
}
if (paren < 0)
{
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nError! Not well formed :( \n-----------------\n");
fprintf(text, "\n\nError! Not well formed :( \n-----------------\n");
}
else
if(isalnum(token))
{
add(pofx, token, count);
count++;
}
else
if(token == '(')
{
push(&s, '(');
}
else
{
if(token == ')')
while((x = pop(&s)) != '(')
{
add(pofx, x, count);
count++;
}
else
if(token == '^')
{
push(&s, token);
}
else
{
while(priority(token) <= priority(top(&s)) && !empty(&s))
{
x = pop(&s);
add(pofx, x, count);
count++;
}
push(&s, token);
}
}
}
else
{
while(!empty(&s))
{
x = pop(&s);
add(pofx, x, count);
count++;
}
}
}
if(form != 0 || paren != 0)
{
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nError! Not well formed :( \n-----------------\n");
fprintf(text, "\n\nError! Not well formed :( \n-----------------\n");
}
else
{
form = -1, paren = 0;
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nPostfix: %s \n\n", pofx);
fprintf(text, "\n\nPostfix: %s\n\n", pofx);
while((token = pofx[z++]) != '\0')
{
three = 1;
if(!isdigit(token) && !isalpha(token))
{
two = popYO();
one = popYO();
switch(token)
{
case '+':
pushYO(one+two); break;
case '-':
pushYO(one-two); break;
case '*':
pushYO(one*two); break;
case '/':
pushYO(one/two); break;
case '^':
if (two > 0)
{
for(i=0;i<two;i++)
{
three = three * one;
}
pushYO(three);
three = 1; break;
}
else
{
for(i=0;i<(two-(2*two));i++)
{
three = three * one;
}
pushYO((1/three));
three = 1; break;
}
}
}
else if(isalpha(token))
{
if(isupper(token))
{
pushYO(token - '#');
}
if(islower(token))
{
pushYO(token - change(token));
}
}
else
{
pushYO(token - '0');
}
}
printf("Result: %lf\n-----------------\n", result[topYO]);
fprintf(text, "Result: %lf\n-----------------\n", result[topYO]);
}
}
}
fclose(text);
fclose(textYO);
printf("\nRun again? \n[1] Yes \n[any other key] No\n");
scanf("%c", &choice);
scanf("%c", &choice);
if(choice == '1')
{
main();
}
else
{
printf("\nThank you for using Kei Shirabe's \ninfix to postfix converter and evaluator! :)\n");
exit(0);
}
}
//other functions down here, not important
Sample text file (and yes there is an extra space at the end):
(1+2))
(1+2*3)
For this text file, the expression (1+2)) is evaluated three times, each result being "Not well formed". The last expression works as expected.
Any help please?

Resources