in this assignment I have to create a tokeniser function in c that copies the contents of a string into another while removing spaces. It returns the position at which the next token should be looked for.
A token is a string of chars or a single operator char.
In my attempt, the counter that detects and bypasses the spaces somehow stops the contents being copied into the result string, after the first token. Here is my code:
int checkOperators(char str[], char operators[], int i){
int counter = 0;
while(operators[counter]!='\0')
{
if(str[i]==operators[counter]) return 1;
counter++;
}
return 0;
}
int tokenise_ops(char str[], int start, char result[], char operators[]){
int i = start;
int j = start;
while(str[i]==' ' && str[i]!='\0'){
i++;
}
if(checkOperators(str,operators,i)==1)
{
result[j]= str[i];
i++;
return i;
}
while(str[i]!='\0')
{
result[j]= str[i];
i++;
j++;
if(str[i]==' ' || checkOperators(str,operators,i)==1) return i;
}
return -1;
}
int main()
{
char str[]="26.6 * 7.9 + 3";
char result[256];
char operators[]={'+','-','*','/','^','\0'};
int start=0;
start = tokenise_ops(str,start,result,operators);
while ( start != -1 )
{
printf("%s\n", result);
start = tokenise_ops(str, start, result,operators);
}
printf("%s\n", result);
return 0;
}
Your tokenize function can be:
int tokenise_ops(char str[], int start, char result[], char operators[])
{
int i = start;
int j = 0;
while ((str[i]==' ') && (str[i]!='\0'))
{
i++;
}
while(str[i]!='\0')
{
if(str[i]==' ' || checkOperators(str,operators,i)==1)
{
printf("Test2: %c\n", str[i]);
result[j] = '\0';
return i;
}
else
{
printf("Test: %c\n", str[i]);
result[j] = str[i];
i++;
j++;
}
}
result[j] = '\0';
return -1;
}
j
is the result
index, so it must start from 0
each callresult
must be null-terminated when the whole str
is parsed.