Reading parentheses from fstream object. C ++
I opened a .txt file with an ifstream object named input
. If the newline starts with "(" then it doesn't read it the way I want it. The expected output is not printed and then exits the loops. I want it to exit the while loop when it reaches the end of the file. What I am doing wrong? My while loop and my .txt are below.
char c;
int i;
do
{
if(input.peek( ) == '(' || input.peek( ) == ')')
{
input >> c;
cout << c;
}else if(input.peek( ) == '+' || input.peek( ) == '-' || input.peek( ) == '*' || input.peek( ) == '/')
{
input >> c;
cout << c;
}else
{
input >> i;
cout << i;
}
}while(input && input.peek( ) != EOF);
Here is the .txt file, each on a separate line:
(3) (3) 4 (5+7)-(5*3)
This is my conclusion:
(3)3
source to share
So, I'm pretty sure the problem is that it input.peek()
returns a newline after reading ')'
. Then it input >> i;
does not read the number, but i
remains the value that it had before, so the output 3
. You can quickly try this by adding i = 42;
before input >> i;
- if the result is (3)42
, then I'm right.
If I am correct, you need to add some code to handle isspace()
or something similar.
May I also suggest you do something like cpeek = input.peek();
before the first if
one and then use if (cpeek == '(' || cpeek == ')')...
etc.
source to share