hi, im a beginner to c++ and just recently got stuck on something.
consider this program:
#include <iostream>
using namespace std;
int main()
{
char ch;
cout << "enter a phrase: ";
while(cin.get(ch))
{
if (ch == '!')
cin.putback('$');
else
cout << ch;
while (cin.peek() == '#')
cin.ignore(1,'#');
}
return 0;
}
so when i run the program and input: its!a!tiny#tiny!world
i get this: its$a$tinytiny$world
which is the expected output
but then i thought, since i have a character variable that i am explicitly declaring and naming, couldn't i just use that instead of cin.peek()?
so i change the program to this:
#include <iostream>
using namespace std;
int main()
{
char ch;
cout << "enter a phrase: ";
while(cin.get(ch))
{
if (ch == '!')
cin.putback('$');
else
cout << ch;
while (ch == '#')
cin.ignore(1,'#');
}
return 0;
}
the only change i made here is on line 11, where i replaced cin.peek() with ch
and when i ran the program again, and gave the same input as before
i got this output: its$a$tiny#
can somebody please explain to me why that is happening? because there seems to be a large gap in my understanding, and any feedback is appreciated.