void readIn(node*& current)
{
string ch; char c;
c=cin.peek(); //works fine here, and I input '('
if (c==')')
{
cin>>ch;
return;
}
elseif(c=='(') //so it goes to here
{
if(current==NULL)
{
cin>>ch; //and takes in the '('
c=cin.peek(); //but then won't prompt me for the next value
//here, it seems to skip over it
if(c != ')')
{
cin>>ch; //but HERE it prompts me for the next value
current=new node;
current->data = atoi(ch.c_str());
current->leftChild=NULL;
current->rightChild=NULL;
readIn(current);
}
}
elseif(current->leftChild==NULL)
readIn(current->leftChild);
elseif(current->rightChild==NULL)
readIn(current->rightChild);
}
}
Here is the struct "node":
1 2 3 4 5 6
struct node
{
int data;
node* leftChild;
node* rightChild;
};
From debugging, I've narrowed down the problem to the "cin.peek()" function. It seems to work the very first time it's called (after my local variable declarations), but then right after the first value is read in (which would be a '(' ), it won't break to ask me to input the next value when cin.peek() is called. It will instead wait for the next regular cin.
I hope I've made my problem clear. Any help to try and solve this problem would be greatly appreciated. :)
For testing purposes I would be tempted to use a std::istringstream for this rather than std::cin.:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <sstream>
void readIn(node*& current, std::istream& is) // make an istream& a parameter
{
// replace all cin with is ...
}
// Now call your function with the data already sitting in a stream
// so you don't need to type it each time.
int main()
{
std::istringstream iss("(5(4(11(7()())(2()())())(8(4()(1()()))(13()())))");
node* n = new node;
readIn(n, iss);
}