Hello, my assignment is to write a postfix calculator. I have written the program. It works well, except for when the user enters in an error. Lets say, user enters "2 A +" it changes the A to a '0'. Which it shouldn't be doing. I have tried strtol() as well, but again, it does the same thing. Is there something else I can do to achieve the same results as atoi() but also not make an 'error' a 0?

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Macro for the size of the stack
#define STACKSIZE  50

// Intiate top and the stack size
long int top = 0;
long int stack[STACKSIZE] = {0};

// Compare the entered string
int stringEqualTo(char *first, char *second)
{
    return (strcmp(first, second) == 0);
}

// Pop function
int pop(void)
{
    long int returnNum;
    
    // Return value on the top of the stack. 
    returnNum = stack[top];
     
    // Move the stack pointer down if not at the lowest point.
    if (top > 0)
    {
        top--;
    }
     
    return returnNum;
}

// Push function
int push(int num)
{
    stack[++top] = num; 
    return num;
}

int main()
{
	char input[50];
	long int numIn;
	long int sum, originalPop, status;
	
	do
	{
			// Read input
			status = scanf("%s", input);
			
			// Convert input to int
			numIn = atoi(input);
			
			if(status != EOF)
			{
				
				if(numIn == 0)
				{
					// Addition
					if(stringEqualTo(input, "+"))
					{
						sum = push(pop() + pop());
					} 
					
					// Subtraction
					else if (stringEqualTo(input, "-")) 
					{
						originalPop = pop();
						sum = push(pop() - originalPop);
					} 
					
					// Multiplication
					else if (stringEqualTo(input, "*")) 
					{
						sum = push(pop() * pop());
					} 
					
					// Division
					else if (stringEqualTo(input, "/")) 
					{
						originalPop = pop();
						sum = push(originalPop / pop());
					}	
				}
				
				else 
				{
					// push the value 'numIn' onto the stack.
					push(numIn);
				}
			}
	}while(status != EOF);
	
	// Print results
	printf("%ld\n", sum);
	
	return 0;
}

Do you or do you not want the user to enter an alphabet?
Do you want the letter to be converted to its ASCII value or some other value or tell the user that he shouldn't enter a letter

Edited 4 Years Ago by zeroliken: n/a

User should only enter number between -2147483646 to 2147483647 and '+'/'-'/'*'/and '/'.

If the user enters an error the program should print "invalid input."

Thank you for the reply.

Before using atoi() you can check each of the values in input is a letter
for example you can create a string containing alphabets as a reference like this:

char ref[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$"; // contains a to z and their corresponding capital letters as well as other unwanted input like other symbols

then you can compare this to your input string to know if it contains a letter

int i,j;
for(i = 0;i<strlen(ref);i++){
    for(j = 0;j<strlen(input);j++){
        if(input[j] == ref[i]){
           printf("Invalid Input");
           break;
        }
    }
}

Then put these in a loop that has a boolean like use, as long as the user input has a letter the program will not continue

P.S. strlen() is from the string.h library you can use numbers to reference the length of the string as a condition for the for loop if you like

Edited 4 Years Ago by zeroliken: n/a

I put that for loop after 51. And I tested the code with "2 A +" it now displays "Invalid Input" at this point the program is still running, then I press <ctrl+d> and it displays "2" and exits the program. I tried putting "break" after the printf statement in the for loop. But it still doesn't exit the program. Is there anyways to make it end the program right after the "invalid input"?

Thanks.

Oh so you want to end the program if the input is invalid

You could make the rest of the code run only if a condition is met
ex.

int main(void){
int i,j, dontrun = 1;
for(i = 0;i<strlen(ref);i++){
    for(j = 0;j<strlen(input);j++){
        if(input[j] == ref[i]){
           printf("Invalid Input");
           dontrun = 0;
           break;
        }
    }
}
    if(dontrun == 1){
       //rest of the codes are here
    }
}

Edited 4 Years Ago by zeroliken: added code tags

atoi() has no way to recover from errors. Use strtol() as subith86 suggested.

Should you actually want to test whether a character is a digit, don't perform contortions; #include <ctype.h> and use isdigit instead.

So, I changed my main() to this. It still doesn't work. The input "2 A +" still gives me "2". It should print "invalid input" and break. Don't know what I'm doing wrong...

int main()
{
	char input[50];
	char ref[] = "0123456789*/+-";
	long int numIn;
	long int sum, originalPop, status, i, j, run;
	
	do
	{
			// Read input
			status = scanf("%s", input);
			for(i = 0; i <= strlen(ref); i++)
			{
				for(j = 0; j <= strlen(input); j++)
				{
					if(input[j] == ref[i])
					{
						run = 1;
					}
					else if(input[j] != ref[i])
					{
						run = 0;
					}
				}
			}
			
			if(run == 1)
			{			
			
				// Convert input to int
				numIn = atoi(input);
				
				if(status != EOF)
				{
					
					if(numIn == 0)
					{
						// Addition
						if(stringEqualTo(input, "+"))
						{
							sum = push(pop() + pop());
						} 
						
						// Subtraction
						else if (stringEqualTo(input, "-")) 
						{
							originalPop = pop();
							sum = push(pop() - originalPop);
						} 
						
						// Multiplication
						else if (stringEqualTo(input, "*")) 
						{
							sum = push(pop() * pop());
						} 
						
						// Division
						else if (stringEqualTo(input, "/")) 
						{
							originalPop = pop();
							sum = push(originalPop / pop());
						}	
					}
					
					else 
					{
						// push the value 'numIn' onto the stack.
						push(numIn);
					}
				}
			}
			else if(run == 0)
			{
				printf("invalid input\n");
				break;
			}
	}while(status != EOF);
	
	// Print results
	printf("%ld\n", sum);

	
	return 0;
}

Nowhere do you properly test for valid input.
In the loop

for(j = 0; j <= strlen(input); j++)
{
    if(input[j] == ref[i])
    {
        run = 1;
    }
    else if(input[j] != ref[i])
    {
        run = 0;
    }
}

you give it a try, but if the last character tested is good, you set the entire input to good. Follow that code with pencil and paper.

In the line status = scanf("%s", input); you
1) return a status but never test it where it does any good.
2) read only up to the first whitespace, so an input of "2 A +" only reads "2".
3) Read this.

Here's the secret to solving most of your errors immediately: printf() !!!
Print values to see what they are at key spots in your code. Displaying input immediately after your scanf() would have shown you what your major problem is.

Also, proper formatting will help a lot in readability. Concentrate on better indentation.

Edited 4 Years Ago by WaltP: n/a

This question has already been answered. Start a new discussion instead.