while loop trouble

Hi there,

I've just started learning C++ and am working on a few small programs with while loops. But I'm having trouble with them in cases where I am trying to run the loop until the end of a variably-long input statement. Here is an excerpt below where I try to output the corresponding telephone digits of a phrase that the user is prompted to input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;

int main()
{
	char digit;
	int counter = 0;

	cout << "Enter a phrase to be converted to telephone number: ";
	cin.get(digit);
	cout << "The converted telephone number is: ";

	while (digit != '\n')
	{
		if ((digit >= 65 && digit <= 67) || (digit >= 97 && digit <= 99))
			cout << "2";
		else if ((digit >= 68 && digit <= 70) || (digit >= 100 && digit <= 102))
			cout << "3";
		else if ((digit >= 71 && digit <= 73) || (digit >= 103 && digit <= 105))
			cout << "4";
		else if ((digit >= 74 && digit <= 76) || (digit >= 106 && digit <= 108))
			cout << "5";
		else if ((digit >= 77 && digit <= 79) || (digit >= 109 && digit <= 111))
			cout << "6";
		else if ((digit >= 80 && digit <= 83) || (digit >= 112 && digit <= 115))
			cout << "7";
		else if ((digit >= 84 && digit <= 86) || (digit >= 116 && digit <= 118))
			cout << "8";
		else if ((digit >= 87 && digit <= 90) || (digit >= 119 && digit <= 122))
			cout << "9";

		counter++;

		if (counter = 7)
			break;

		cin.clear();
		cin.get(digit);
	}

	cout << endl;
	if (counter < 7)
		cout << "Not enough letters to complete a full 7-digit number" << endl;
	if (counter > 7)
		cout << "Only the first 7 letters were used" << endl;

	return 0;
}


When I run this program, it builds without errors but only outputs the digit of the first letter typed. It seems to be getting stuck somewhere in the while loop but I just can't figure out why. Any suggestions?

(Please note I'm a new programmer so my vocabulary of c++ commands is quite small. Currently working through Malik 3rd edition, ch5 - repetition control structures)
Last edited on
You used the assignment operator '=' instead of the comparison operator '==' on line 34.

So, line 34 sets counter equal to 7 and then breaks out of the while loop.
Aha!! That fixes everything. I feel silly. Thank you for your help =)
Topic archived. No new replies allowed.