Problem with cin.peek()

Hello,
I am writing a program which requires me to read in input and build a binary tree from it. The input is in the form:

empty tree::= ()
tree::= empty tree | (integer tree tree)

An example would be:
(5(4(11(7()())(2()())())(8(4()(1()()))(13()())))

Here is my readIn function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
void readIn(node*& current) 
	{
	  string ch; char c;
	  c=cin.peek();        //works fine here, and I input '('
	  if (c==')') 
	   {
	     cin>>ch;
	     return;
           }
	   else if(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);	
					}
		   }
		else if(current->leftChild==NULL)
		   readIn(current->leftChild);
				
		else if(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. :)
Last edited on
You have to type all your data in on one line.
Oh wow. I feel dumb. Of course. Thank you :)
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);
}
If you know that you are reading a number, why don't you read it as a number instead of converting from a string?
1
2
3
4
5
6
7
8
cin>>ch;       //and takes in the '('
c=cin.peek(); 
if(c != ')'){ //or if(c >='0' && c<='9')
  //cin>>ch;
  //current->data = atoi(ch.c_str());
  cin >> current->data;
//...
}
Last edited on
Topic archived. No new replies allowed.