pvjc24/a1/program.c
2024-03-23 19:10:08 +01:00

143 lines
3.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#define SIZE 1000
typedef struct{
char* p_na_line;
struct link* p_na_next_struct;
}link;
int main()
{
link* pointer_to_start_of_chain = malloc(sizeof(link));
memset(pointer_to_start_of_chain,0,sizeof(link));
int read_lines = reading_strings_and_storing_them_in_memory(pointer_to_start_of_chain);
if(read_lines==0){
return 0;
}
int result=0;
link* next_link = pointer_to_start_of_chain;
while(next_link != NULL){
result=analizing_string(next_link->p_na_line);
if(result==0){
printf("ZLE\n");
}else if(result==1){
printf("OK\n");
}else{
printf("CHYBA\n");
}
free(next_link->p_na_line);
link* ptr=next_link;
next_link=next_link->p_na_next_struct;
free(ptr);
}
return 0;
}
int reading_strings_and_storing_them_in_memory(link* pointer_to_start_of_chain){
link* next_link = pointer_to_start_of_chain;
char buffer[SIZE];
link* ancestor=NULL;
int counter=0;
while(1){
if(fgets(buffer, SIZE, stdin)==NULL||buffer[0]=='\n'){
free(next_link);
if(ancestor!=NULL){
ancestor->p_na_next_struct=NULL;
}
break;
}
int size=strlen(buffer)+1;
next_link->p_na_line=malloc(size);
next_link->p_na_next_struct=malloc(sizeof(link));
memcpy(next_link->p_na_line, buffer,size);
ancestor=next_link;
next_link=next_link->p_na_next_struct;
counter++;
}
return counter;
}
int analizing_string(char* pointer){
char token1[SIZE];
char token2[SIZE];
char token3[SIZE];
float number1, number2, result3;
char buffer_for_token[SIZE];
strcpy(buffer_for_token,pointer);
int counter=0;
char operant;
int i=0;
while(pointer[i]!='\0'){
if(pointer[i]=='+'||pointer[i]=='/'||pointer[i]=='*'||pointer[i]=='-'){
operant=pointer[i];
counter++;
if(counter>1){
return -1;
}
}
i++;
}
char delim[] =" +=-*/\n";
char *first_number_cucumber=strtok(buffer_for_token, delim);
if(first_number_cucumber==NULL) {//||is_number_question_mark(first_number_cucumber)==0){
return -1;
}
strcpy(token1, first_number_cucumber);
char *second_number=strtok(NULL, delim);
if(second_number==NULL) { //||is_number_question_mark(second_number)==0){
return -1;
}
strcpy(token2, second_number);
char *result_token=strtok(NULL, delim);
if(result_token==NULL) { //||is_number_question_mark(result)==0){
return -1;
}
strcpy(token3, result_token);
char *token = strtok(NULL, delim);
if(token!=NULL){
return -1;
}
number1=atof(token1);
number2=atof(token2);
result3=atof(token3);
if(operant=='+' &&result3==number1+number2){
return 1;
}
if(operant=='-'&&(result3==number1-number2)){
return 1;
}
if(operant=='*'&&(result3==number1*number2)){
return 1;
}
if(operant=='/'&&(result3==number1/number2)){
return 1;
}
return 0;
}
/*int is_number_question_mark(char *pointer){
for(int i=0; pointer[i]!='\0'; i++){
if (!isdigit(pointer[i])&&pointer[i]!='.'&&pointer[i]!=',') {
return 0;
}
}
return 1;
}*/