I am trying to write RPN calculator, but I've been struggling with getting arguments from user. What I want to do is: take whole line, split it to tokens and put it to array. I have something like below, but it works only once. On the second while-loop performing line is taken, but arr==NULL
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_str 100
char* getLine(){
char* line = malloc(MAX_str*sizeof(char*));
return fgets(line, MAX_str,stdin);
}
char** toArray(char* line){
int i=0;
char** array= malloc(MAX_str*sizeof(char*));
array[i] = strtok(line," \t");
while(array[i]!=NULL){
array[++i] = strtok(NULL,"");
}
return array;
}
int main(){
char* linia;
char** arr;
int i=0,end=0;
while(!end){
linia=getLine();
arr = toArray(linia);
while(arr[i]!=NULL){
printf("%s\n",arr[i]);
i++;
}
free(linia);
free(arr);
}
}
Secondly, strtok
splits only on two tokens, for example
>1 2 3
gives:
>1
>2 3