I opened a .txt file with an ifstream object named input. If a new line starts with a “(” then it doesn’t read it how I want it to. The expected output doesn’t get printed, then it exits the loops. I want it to only jump out of the while loop when it reaches the end of the file. What am I doing wrong? My do while loop and my .txt file 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 output:
(3)3
So, I’m pretty certain that the problem is that
input.peek()is returning a newline after')'has been read. Theninput >> i;doesn’t read a number, andiremains the value it had before, so the output is3. You could quickly try this by addingi = 42;beforeinput >> i;– if the output becomes(3)42, then I’m right.If I’m right, you will want to add a bit of code to handle
isspace()or something similar.May I also suggest that you do something like
cpeek = input.peek();, before the firstif, and then useif (cpeek == '(' || cpeek == ')')...etc.