Hello!

I want to split a mathematical expression 3 + 4 ( 5 * 8 )
into tokens by using space as a splitting mode. e.g
3
+
4
(
5
and so on.
But when I write

string exp;
char space[]=" ";

result=strtok(exp,space);

the compiler gives the error at the 3rd line that:
'strtok' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'char *'


Is there any problem with the data types of exp and space?

Please help me!

Recommended Answers

All 6 Replies

You need to use the .c_str() member of the std::string class to generate a NULL-terminated C-style "string" from the memory the std::string class is managing for you.

I would also suggest a polymorphic approach to parsing expressions like that, specifically using polymorphically a member function to return the result of a simple (what I will call) "term" of the form: n * b

ex:
3 * 5
or
1235 + 41236
or
-1000 - 342345

etc.

But then again, you don't have to listen to every fool willing to type--and I don't even know that's what you're doing.

don't use strtok() because it will put 0s in the std::string buffer, invalidating that buffer.

Instead, use std::string's find() method to locate the spaces, the substr() to extract the characters.

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    std::stringstream expression(" 3 + 4 ( 5 * 8 ");
    std::string token;

    const char DELIMITER(' ');

    while (std::getline(expression, token, DELIMITER))
    {
        std::cout << token << std::endl;
    }
}
const char DELIMITER(' ');

There is no need to provide a delimiter of whitespace explicitly. Standard streams (std::cin, std::stringstream) parse on whitespace by default. For example:

#include <iostream>
#include <sstream>
#include <string>

int main () {

    std::stringstream expr("3 + 4 * ( 5 * 8 )");
    std::string token;
    while (expr >> token)
        std::cout << token << std::endl;
    return 0;
}

You may want to look at using the substr method and the find method for std::strings to help break strings apart.

You may want to look at using the substr method and the find method for std::strings to help break strings apart.

I already suggested that yesterday, but I think using stringstream is a better solution.

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.