1

I am trying to code a Binary tree and am currently trying to get an 'inorder' function to work which takes in a binary tree containing integers and outputs the binary tree to a string in numerical order. However when I try to concatenate the integer to the end of the string I am receiving the error message "Error C2440: 'type cast' : cannot convert from 'int' to 'std::string'.

The code for the function is as follows:

void _inorder(node *tree, string &str)
{   
        if (tree != NULL)
        {
            _inorder(tree->left, str);
            str = str + (string)(tree->data);
            _inorder(tree->right, str);
        }

        cout << str << endl;
}
2
  • unrelated : use a function visit_node so your _inorder function can work with other elements or do something else Commented Apr 20, 2016 at 10:13
  • When you get an error message, you should at least read it to see which line it refers to (and mention that here). Thanks. Commented Apr 20, 2016 at 11:50

3 Answers 3

4

Use std::to_string(since c++ 11) to convert the int to a string.

str = str + std::to_string(tree->data);
Sign up to request clarification or add additional context in comments.

1 Comment

Note: This is a C++11 feature, so it might not be available everywhere.
2

Before c++11, you can do this:

ostringstream os;
os << tree->data;
str += os.str();

Comments

0

use this function

  std::to_string(int);

This should resolve the error.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.