0

I got is c++ code below.

#include <iostream>
using namespace std;
int main()
{
char ch;
int ct1, ct2;
ct1 = ct2 = 0;
while ((ch = cin.get()) != '$')
{
    cout << ch;
    ct1++;
    if (ch = '$')
        ct2++;
    cout << ch;
}
cout << "ct1 = " << ct1 << ", ct2 = " << ct2 << "\n";
system("pause");
return 0;
}

Now you can tell what gonna happen if input.

  hi$<ENTER>

and the the output should be this right.

hi ct1 = 2, ct2 = 0

But the real output is this.

h$i$ct1 = 2, ct2 = 2.

why is it outputting that i don't understand and how should i fix it.

and i'm using Visual Studio Express 2013 preview for windows desktop.

fish_shoes
  • 115
  • 9
  • 3
    You have `if (ch = '$')`. That's an assignment, not a comparison, so it counts as `true` in every iteration of the loop. You want `if (ch == '$')` instead. – jogojapan Jul 12 '13 at 11:19
  • 2
    This question is about a typo (or something similar). Voting to put on hold. – jogojapan Jul 12 '13 at 11:22
  • `ch` should have type `int` (or you should write `while ( cin.get() && ch != '$' )`; as written, you'll go into an endless loop if you reach end of file. – James Kanze Jul 12 '13 at 11:23
  • 1
    Also, if you really mean `if ( ch == '$' )` in the loop, the condition will always be false (since you don't enter the loop if `ch == '$'). – James Kanze Jul 12 '13 at 11:25
  • I just realized my comment is a bit misleading. The assignment of course does not necessarily evaluate to `true`. It evaluates to whatever is assigned, which is `$`, and that evaluates to `true` because it is not zero. – jogojapan Jul 12 '13 at 11:27

4 Answers4

2

first, there is a problem in this code, if(ch = '$'), second, I think the real output is "hhct1 = 1,ct2 = 0", because when the char is equal to '$', can get into the loop.

liuan
  • 299
  • 1
  • 3
  • 9
0

In your if statement, you actually assigned $ to ch : if(ch = '$'). This should be :

if(ch == '$')

Also, your real output will be like this : hhiict1 = 2, ct2 = 0, since you wrote cout << ch; two times in your while statement.

Matthieu Harlé
  • 739
  • 1
  • 13
  • 32
0

You are using assignment operator = instead of == in if condition. I would recommend.

if('$' == ch)
praks411
  • 1,972
  • 16
  • 23
0
while ((ch = cin.get()) != '$')
{
    cout << ch;
    ct1++;
    if (ch = '$') // << here is the heck
          ^^^     // did you mean == ?
        ct2++;
    cout << ch;
}
4pie0
  • 29,204
  • 9
  • 82
  • 118