Hi all, I am writing a program to make a binary tree. I have all the class/structure part fine, I just want to make the program unbreakable. I am asking the user to input strings, and I am putting those strings into the tree as all lower case (I also have this done as well). What I wanted to know is how would I make sure that they input a qualifying string. If they insert like numbers, for example, to display that it is bad data, and ask them to try again... I tried this, but it didn't work.

void add_node(Tree tree, int count)
{
  char again;
  string word;

  cout << "Please enter a word: ";
  cin >> word;

  if (cin.fail())
    {
      cin.clear();
      cout << "Not a valid input for the Binary Tree Mister!" << endl;
      add_node(tree, count);
    }  
  to_lower(word);
  
  if (count == 0)
    {
      tree.add(word);
      count++;
    }
  else
    {
      tree.add(tree.get_root(), word);
    } 
  
  cout << "Would you like to enter another word?";
  cin >> again;
  tolower(again);
  
  if (again == 'y')
    {
      add_node(tree, count);
    }  
  else 
    {
      Menu(tree, count);
    }
}

There's a saying about C/C++ that goes something like: "There is no such thing as a bad string." That usually is trumpeted when input is tried as a numerical value and you want to validate it. That is, you should accept the numerical information input as a string and then convert it to the desired type if the input is valid. Unfortunately, this tends to work against your situation in that all information entered from the keyboard or in a file is valid in a string as long as it is in the character set that is being used by your compiler. So, to check for an invalid string you have to define what is invalid and check for it. So, if you decide that digits are invalid in strings or that characters like # or ~ or * are invalid in strings, then do a character by character evaluation fo the string contents and look for any invalid characters. If you want to check for valid words, then develop a dictionary of valid words and screen that the input is in the valid list. Etc.

Ok, sounds good thanks for the insight.

To that end, you may find the find_first_of() string member function useful

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.