So what I want the code to do so far is take an expression lets say 35x + 17y = 5 and break it down into three values, 2 integers and a character. 35, 17, and + so I can tell it how to evaluate it. Here is my code so far

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

int main(void)
{
	char * exp;
	char * tok;

	printf("Enter an expression: ");
	scanf("%s", &exp);

	tok = strtok(exp, " x+-y=");

	while (tok != NULL)
	{
		printf ("%s\n",tok);
		tok = strtok (NULL, " x+-y=");
	}
}

I get an error with strtok saying that the expression cannot be evaluated

> scanf("%s", &exp);
This line is the problem. First, exp is an uninitialized pointer. As soon as scanf begins writing characters to whatever address exp points to, a segmentation fault is likely. Next, scanf stops reading on whitespace for the %s specifier. With your sample data of "35x + 17y = 5", only "35x" will be stored in exp.

Use an array and fgets to read the whole line and the tokenizer should work better.

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

int main(void)
{
    char exp[BUFSIZ];

    printf("Enter an expression: ");

    if (fgets(exp, sizeof exp, stdin)) {
        char *tok = strtok(exp, " x+-y=");

        while (tok != NULL)
        {
            printf ("%s\n",tok);
            tok = strtok (NULL, " x+-y=");
        }
    }

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.