0

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

Edited by Kombat: n/a

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by Radical Edward
0

> 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;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.