954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Handeling errors with atoi()

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;
}
sync101
Newbie Poster
6 posts since Jan 2012
Reputation Points: 10
Solved Threads: 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

zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
 

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.

sync101
Newbie Poster
6 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

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

zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
 

check this link, this should help you
http://linux.die.net/man/3/strtol

For C++ programmers, there is another solution
http://www.cplusplus.com/articles/numb_to_text/

subith86
Junior Poster
124 posts since Mar 2011
Reputation Points: 30
Solved Threads: 14
 

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 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.

sync101
Newbie Poster
6 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

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
    }
}
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
 

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 and use isdigit instead.

Trentacle
Junior Poster in Training
72 posts since Dec 2010
Reputation Points: 110
Solved Threads: 20
 

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;
}
sync101
Newbie Poster
6 posts since Jan 2012
Reputation Points: 10
Solved Threads: 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. Displayinginput immediately after your scanf() would have shown you what your major problem is.

Also,[url=http://www.gidnetwork.com/b-38.html]proper formatting will help a lot in readability. Concentrate on better indentation.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You