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;
}
farzadshbfn
  • 2,710
  • 1
  • 18
  • 38
S Edgar
  • 19
  • 2
  • unrelated : use a function visit_node so your _inorder function can work with other elements or do something else – UmNyobe Apr 20 '16 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. – Toby Speight Apr 20 '16 at 11:50

3 Answers3

4

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

str = str + std::to_string(tree->data);
Biruk Abebe
  • 2,235
  • 1
  • 13
  • 24
2

Before c++11, you can do this:

ostringstream os;
os << tree->data;
str += os.str();
loafbit
  • 33
  • 6
0

use this function

  std::to_string(int);

This should resolve the error.

piyushj
  • 1,546
  • 5
  • 21
  • 29