Question about "iostream"

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
User avatar
Yile
New poster
Posts: 17
Joined: Sun Feb 27, 2005 10:36 am
Location: China

Question about "iostream"

Post by Yile » Tue May 10, 2005 11:58 am

My C program runs well. But when I modify it to C++ version, it doesn't work. The reason is that I don't understand the "iostream" very well.
This is my program which is used to input a Tree from keyboard. For example:

Code: Select all

if the tree is:
    1
   /
  2
 / \
3   4

Then I can input :
 (1 (2 (3 () () ) (4 () () ) ) () )
This is my C program which is all right:

Code: Select all

#include <stdio.h>
int main(){
  char c;
  int left=0,right=0;
  int v;
  while(left>right || left==0){
    c=getchar();
    while(c!='(' && c!=')')
      c=getchar();
    if(c=='('){
      left++;
      putchar(c);
      if(scanf("%d",&v))
		printf("%d",v);
    }
    else{
      right++;
      putchar(c);
    }
  }
  return 0;
}
But the C++ version doesn't work:

Code: Select all

#include <iostream.h>
int main(){
  char c;
  int left=0,right=0;
  int v;
  while(left>right || left==0){
    cin.get(c);
    while(c!='(' && c!=')')
      cin.get(c);
    if(c=='('){
      left++;
      cout<<c;
      if(cin>>v)
		cout<<v;
    }
    else{
      right++;
      cout<<c;
    }
  }
  return 0;
}
What's the matter?

Post Reply

Return to “C++”