Update cv3/program.c

This commit is contained in:
Yurii Chechur 2024-10-14 10:58:47 +00:00
parent f66396c189
commit a16b56dd33

View File

@ -47,17 +47,18 @@ int read(struct stack *s) {
// Read a line of input // Read a line of input
if (fgets(temp, sizeof(temp), stdin) == NULL) { if (fgets(temp, sizeof(temp), stdin) == NULL) {
return 0; // Error reading input printf("no input\n");
return 0; // Error reading input or end of input
} }
// Check for empty input // Check for empty input
if (strcmp(temp, "\n") == 0) { if (strcmp(temp, "\n") == 0) {
printf("no input\n"); return 1; // Continue to next iteration
exit(1); // Exit on empty input
} }
// Check for termination input // Check for termination input
if (strcmp(temp, "end\n") == 0) { if (strcmp(temp, "end\n") == 0) {
printf("no input\n"); // Print "no input" upon end
return 0; return 0;
} }
@ -67,24 +68,22 @@ int read(struct stack *s) {
// If it's a number // If it's a number
if (scan == 1) { if (scan == 1) {
push_stack(s, value); push_stack(s, value);
print_stack(s); // Print the stack after adding print_stack(s);
} else { } else {
// If it's an operator
switch (temp[0]) { switch (temp[0]) {
case '+': case '+':
case '-': case '-':
case '*': case '*':
case '/': { case '/': {
// Check for sufficient values in the stack
if (s->size < 2) { if (s->size < 2) {
printf("no input\n"); printf("no input\n");
return 1; // Don't exit; continue to next iteration return 1; // Continue to next iteration
} }
float b = pop_stack(s); // Pop the last two values float b = pop_stack(s);
float a = pop_stack(s); float a = pop_stack(s);
float result; float result;
switch (temp[0]) { switch (temp[0]) {
case '+': result = a + b; break; case '+': result = a + b; break;
case '-': result = a - b; break; case '-': result = a - b; break;
@ -92,20 +91,18 @@ int read(struct stack *s) {
case '/': case '/':
if (b == 0) { if (b == 0) {
printf("division by zero\n"); printf("division by zero\n");
exit(0); // Exit on division by zero return 1;
} }
result = a / b; result = a / b;
break; break;
} }
push_stack(s, result); // Push the result back onto the stack push_stack(s, result);
print_stack(s); // Print the stack after operation print_stack(s);
//printf("no input\n"); // Print the "no input" message return 1; // Continue without printing "no input"
// exit(0); // Exit the program after the operation
break;
} }
default: default:
printf("bad input\n"); printf("bad input\n");
exit(0); // Exit on invalid input return 1; // Continue on invalid input
} }
} }