trouble in do/while loop

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
int main( int argc, char* argv[] ) {

	short rotaction;

	char thischar;

	bool dorot5=false;

	bool dorot13=false;





// command line parsing deleted

	do {
		cin >> thischar;



		if ( dorot5 && thischar >= '0' && thischar < '5' ) {

			thischar = thischar + 5;

			cout << thischar;

			continue;

		};



		if ( dorot5 && thischar > '4' && thischar <= '9' ) {

			thischar = thischar - 5;

			cout << thischar;

			continue;

		};



		if ( dorot13 && thischar >= 'A' && thischar < 'N' ) {

			thischar = thischar + 13;

			cout << thischar;

			continue;

		};

			

		if ( dorot13 && thischar >= 'a' && thischar < 'n' ) {

			thischar = thischar + 13;

			cout << thischar;

			continue;

		};

			

		if ( dorot13 && thischar > 'M' && thischar <= 'Z' ) {

			thischar = thischar - 13;

			cout << thischar;

			continue;

		};

			

		if ( dorot13 && thischar > 'm' && thischar <= 'z' ) {

			thischar = thischar - 13;

			cout << thischar;

			continue;

		};

			

		cout << thischar;

		

		} while ( cin.good() > 0 );


	cout << endl;

	return 0;

}


When I type
 
echo abcdwxyz1234567890 | rot

I find 1 extra character is output. How do I get rid of it?
Last edited on
The do-while executes, then checks the while condition. So when cin.good() returns something <=0, it has already executed the iteration for that case. Thus, the single extra character.

You could get rid of the do, and just make a while loop. This will check the condition before each iteration, thus if cin.good() is bad, you don't execute. You would have to put one cin>>thischar before the loop to get a valid cin.good(), then the loop will check the condition before each iteration.

Or maybe if you put one cin>>thischar before your do-while, then move the one you already have to the end of the loop, right after the cout. It's probably better to do it the first way though, that way it will bail out even if the very first input is bad.
1
2
3
4
5
6
while( true )
{
    cin >> thischar;
    if( !cin.good() ) break;
    ...
}
Last edited on
I did switch to a while loop and added the cin >> thischar before the loop. This made me lose the first character of input.

Next I removed cin >> thischar from the top of the loop and put it after each cout << thischar inside the loop.
Topic archived. No new replies allowed.