I'm writing a C program that reads a file given as input. I should create a calculator, each line of the file is composed like this:
*2
+6
-8
+33
.......
I was trying to use strtok to separate operation from number. My problem is that strtok doesn't behave as it should. Why does my program always enter all ifs?
typedef struct{
long result;
long number;
char done;
}shm_data;
void create_operation(char* buffer,shm_data* data){
char* add,*sottr,* molt;
long number=0;
if(((add=strtok(buffer,"+"))!=NULL))
{
printf("add: %s\n",add);
}
if(((sottr=strtok(buffer,"-"))!=NULL))
{
printf("sottr: %s\n",sottr);
}
if(((molt=strtok(buffer,"*"))!=NULL))
{
printf("molt: %s\n",molt);
}
}
void child_mng(shm_data* data,int sem_id,char* path){
FILE* r_stream;
char tmp[DIM];
if((r_stream=fopen(path,"r"))==NULL)
{
perror("fopen");
exit(1);
}
while(fgets(tmp,DIM,r_stream))
{
if(tmp[strlen(tmp)-1]=='\n')
tmp[strlen(tmp)-1]='\0';
printf("read file: %s\n",tmp);
create_operation(tmp,data);
}
exit(0);
}
es.
Suppose the file contains only one line:
+80
This is my output:
./calculator list.txt
read file: +80
add: 80
sottr: +80
molt: +80
but the output should be this:
./calculator list.txt
read file: +80
add: 80
why does this happen? Could I do it differently?