My program that uses putback() doesn't work. What am I doing wrong?

I'm trying to write a program that switches ! for $ and whenever it encounters # just ignores it; however, i get a weird output.
When I write: Now!is#the!time#for!fun#!
I should get: Now$isthe$timefor$fun$
But instead I get: Nwitetmfrfn
What am I doing wrong?
Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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;
}


Thanks!
Consider using cin.peek() to see what is in the buffer before getting it with cin.get()
I followed your suggestions and rewrote the program here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
	char ch;

	cout << "Enter a phrase: ";
	cout << cin.peek() << endl;
	while (cin.get(ch))
	{
		if(ch == '!')
		cin.putback('$');
		else
		cout << ch;
		while (cin.peek() == '#');
		cin.ignore(1,'#');
	}
	return 0;
}


And the output:
Enter a phrase: Now$isthe$timefor$fun$
78
Nwitetmfrfn
You are still using putback(). Try what Galik suggested; peek() returns the character you would get if you use get().
I'm having trouble understanding where to use peek()? After which line? And can you please provide the syntax like do I do:
cout << cin.peek() << endl; (after line 11)
By the way that's what I tried and got:

Enter the phrase: Now!is#the!time#for!fun#!
Nwitetmfrfn

So I'm obviously doing something wrong I just don't know what :(
while (cin.peek() == '#'); You've got a semicolon at the end. So you're ignoring 1 character every time.
Actually while (cin.peek() == '#'); will loop indefinitely because peek() never removes the '#'. Try this:

 
while (cin.peek() == '#') // no semicolon 


EDIT: fixed
Last edited on
Great! That worked. You guys are the best, I still haven't had a question unanswered here. Thanks again :)
Topic archived. No new replies allowed.