0
votes

i'm coding a calculator which works on cmd. i'm mostly finished for +,-,/,* operations and two numbers but i have this error. i looked for this error but all of the documents are about file functions. i don't use file func. but still i get this error:

debug assertion failed! program: ...all studio2012.... file:f:\dd\vctools\crt_bld\self_x86\crt\srt\strtol.c line:94

expression: nptr !=NULL

codes are:

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

char define(char input[]);
float math(int sayi[], char operation);

void main()
{
int sayi[100];
char input[100];
char inputCpy[100];
const char functions[] = "+,-,/,*";
char *token;
char operation;
float result;
int i=1;

printf("welcome to my simple cmd calculator!\n what do you want to know?\n");
scanf("%s", input);
strcpy(inputCpy,input);
token = strtok(input, functions);
sayi[0]=atoi(token);
while( token != NULL ) 
{
    token = strtok(NULL, functions);
    sayi[i]=atoi(token);
    i++;
}
printf ("sayi1=%d sayi2=%d", sayi[0], sayi[1]);
operation = define(inputCpy);
printf("operation = %c\n", operation);
result = math(sayi,operation);
printf ("result = %.2f\n", result);
system("pause");
}

char define(char input[])
{
char operation;
for (int i=0; i<strlen(input); i++)
{
    if(!isdigit(input[i]))
    {
        operation = input[i];
        break;
    }
}
return operation;
}

float math(int sayi[], char operation)
{
float result=0;
switch(operation)
        {
        case '+':
            result = sayi[0]+sayi[1];
            break;

        case '-':
            result = sayi[0]-sayi[1];
            break;

        case '*':
            result = sayi[0]*sayi[1];
            break;

        case '/':
            if(sayi[1]!='0')
                {
                result = sayi[0]/sayi[1];
                }
            else
                {
                printf ("wtf!! you can't divide by 0!");
                }
            break;
        default:
            printf("did you mean \"i don't know maths\"");
        }
return result;
}
2

2 Answers

0
votes
token = strtok(input, functions);

You need to check the return value of strtok otherwise you may pass a null pointer to atoi. Same later in your code with token = strtok(NULL, functions);

0
votes

You need to check whether token is NULL before calling atoi(token).

Change the lines:

token = strtok(input, functions);
sayi[0]=atoi(token);
while( token != NULL ) 
{
    token = strtok(NULL, functions);
    sayi[i]=atoi(token); // token will eventually be NULL
                         // and you run into a problem here.
    i++;
}

to:

token = strtok(input, functions);
i = 0;
while( token != NULL ) 
{
   sayi[i]=atoi(token);
   token = strtok(NULL, functions);
   i++;
}